Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

后端 未结 24 1959
无人共我
无人共我 2020-11-22 06:13

I have this section defined in my _Layout.cshtml

@RenderSection(\"Scripts\", false)

I can easily use it from a view:

24条回答
  •  不要未来只要你来
    2020-11-22 06:58

    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.

提交回复
热议问题