Search code examples
c#asp.net-mvcasp.net-mvc-5asp.net-mvc-partialview

How to render partial Views Sections in main layout file


I am using asp.net MVC 5.

I have a _layout file as follows:

    <!DOCTYPE html>
<html lang="en">
<head>
    @Html.Partial("_Head")
    @RenderSection("styles", required: false)
</head>

<body>
   @RenderBody()
 @RenderSection("scripts", required: false)

</body>
</html>

I then have my main view:

@{
  Layout = "~/Views/Shared/_Layout.cshtml";
  Title = "mainView"
}

  <div class="partialcontents" data-url="/user/UserList"></div>

$(document).ready(function (e) {
            $(".partialcontents").each(
                function (index, item) {
                    var url = $(item).data("url");
                    if (url && url.length > 0) {
                        $(item).load(url, function () { $(this).css("background-image", "none"); });
                    }
                }
            );
        });

and here is my partial view:

@{

}
<p> Partial View</p>

@section scripts
{
  @Scripts.Render("~/bundles/script/datatable")
}


My controller that renders the partial view:


[Authorize]
        public ActionResult UserList(UsersViewModel model, string sortOrder, string currentFilter, string searchString, int? page)
        {
.... removed for simplicity
 return PartialView("_UserList", new UsersViewModel()
            {
                Users = users.ToPagedList(pageNumber, pageSize)
            });
}

So now my issue is that the section from the partial view is not being rendered in the main layout file. I understand why I think...

Its because I am rendering it in another controller. and then passing it along.

But how can I get this right?


Solution

  • You should place:

    @section scripts
    {
        @Scripts.Render("~/bundles/script/datatable")
    }
    

    in the main view, because AJAX requests return only partial without layout so MVC doesn't know where it should render this script section. In this AJAX request @RenderSection("scripts", required: false) is never evaluated. If you omit @section scripts in your partial, it would probably work, but this is a not good approach to include JS in AJAX responses, so don't do that if you don't need too.