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

后端 未结 24 1667
无人共我
无人共我 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:51

    This is quite a popular question, so I'll post my solution up.

    I had the same problem and although it isn't ideal, I think it actually works quite well and doesn't make the partial dependant on the view.

    My scenario was that an action was accessible by itself but also could be embedded into a a view - a google map.

    In my _layout I have:

    @RenderSection("body_scripts", false)
    

    In my index view I have:

    @Html.Partial("Clients")
    @section body_scripts
    {
        @Html.Partial("Clients_Scripts")
    }
    

    In my clients view I have (all the map and assoc. html):

    @section body_scripts
    {
        @Html.Partial("Clients_Scripts")
    }
    

    My Clients_Scripts view contains the javascript to be rendered onto the page.

    This way my script is isolated and can be rendered into the page where required, with the body_scripts tag only being rendered on the first occurrence that the razor view engine finds it.

    That lets me have everything separated - it's a solution that works quite well for me, others may have issues with it, but it does patch the "by design" hole.

提交回复
热议问题