2

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?

tereško
  • 58,060
  • 25
  • 98
  • 150
Zapnologica
  • 22,170
  • 44
  • 158
  • 253
  • As per the above details, I didn't find any partial view other than _Head @Html.Partial("_Head") within layout page. I didn't find any view which using "_UserList" partial view. – Bhasyakarulu Kottakota Oct 02 '14 at 11:20
  • 1
    Possible duplicate of [Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine](http://stackoverflow.com/q/7556400/1199711) – Zabavsky Oct 02 '14 at 11:31

1 Answers1

3

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.

Andrew
  • 307
  • 7
  • 13
py3r3str
  • 1,879
  • 18
  • 23