Home > Enterprise >  ASP.NET Core 6 MVC ajax render view in Body Section
ASP.NET Core 6 MVC ajax render view in Body Section

Time:09-29

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  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" >
            @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?

CodePudding user response:

in view

<script type="text/jscript">     
$(document).ready(function () {        
    $("#partialviews").load('/controller/actionmethod');        
});        

in controller

public PartialViewResult ActionMethod()
{
    return PartialView("_partialviewname");
}

CodePudding user response:

return View("Index", header);

Because you return view, so the the entire layout is rendered again in the body section.

You can create a new action to display the content.

HomeController:

 public IActionResult Index()
        {
            return View();            
        }
        
        public ContentResult TestData(string header)
        {
            header = "sss";
            return Content(header, "text/plain");
        }

Layout:

<div>
        <main  id="main" role="main" >
            @RenderBody()    
        </main>       
    </div>     
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
         $(document).ready(function () {
      
                $.ajax({
                    type: 'GET',
                    url: '/home/TestData/',
                    success: function (result) {
                        $('#main').html(result);
                    }
                });
            });     
   </script>

Result:

enter image description here

  • Related