I have this section defined in my _Layout.cshtml
@RenderSection(\"Scripts\", false)
I can easily use it from a view:
I ran into a nearly identical problem the other day, except that the partial view was a response to an AJAX request. In my situation, the partial was actually a full page, but I wanted it to be accessible as a partial from other pages.
If you want to render sections in a partial, the cleanest solution is to create a new layout and use a ViewBag variable. This does not work with @Html.Partial()
or the new
, use AJAX.
Main view (that you want to be rendered as a partial elsewhere):
@if(ViewBag.Partial == true) {
Layout = "_layoutPartial";
}
[...]
@section Scripts {
}
Controller:
public IActionResult GetPartial() {
ViewBag.Partial = true;
//Do not return PartialView!
return View("/path/to/view")
}
_layoutPartial.cshtml (new):
@RenderSection("Scripts")
@RenderBody()
Then use AJAX in your page.
If you want to render the page in the main layout (not a partial), then don't set ViewBag.Partial = true
. No HTML helpers necessary.