I am creating an ASP.NET Core 6 MVC application.
In my _Layout.cshtml
I have a menu that the option calls a method in the controller that renders a View in @RenderBody()
Simplifying, the menu is like this
<li><a class="nav-link link-light" asp-controller="Employer" asp-action="Index">Employer Setup</a></li>
The controller is like this
public IActionResult Index()
{
var sessionValue = HttpContext.Session.GetString("Header");
HeaderViewModel header = JsonSerializer.Deserialize<HeaderViewModel>(sessionValue);
return View("Index", header);
}
Under certain circumstances, I also need to call this action by Ajax. I have define this in my _Layout.cshtml
:
<div>
<main id="main" role="main" class="pb-3">
@RenderBody()
</main>
</div>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$.ajax(
{
type:"POST",
url: '@Url.Action("Index", "Employer")',
success:function(result){
$("#main").html(result);
},
}
);
</script>
The problem I have is that the controller returns a view, so the entire layout is rendered again in the body section, instead of rendering only the new view. So I have to return a partial view instead of a view.
I do not want to duplicate the method to retrieve the same data.
Is there a way to return a view?