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

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

    The goal of the OP is that he wants to define inline scripts into his Partial View, which I assume that this script is specific only to that Partial View, and have that block included into his script section.

    I get that he wants to have that Partial View to be self contained. The idea is similar to components when using Angular.

    My way would be to just keep the scripts inside the Partial View as is. Now the problem with that is when calling Partial View, it may execute the script in there before all other scripts (which is typically added to the bottom of the layout page). In that case, you just have the Partial View script wait for the other scripts. There are several ways to do this. The simplest one, which I've used before, is using an event on body.

    On my layout, I would have something on the bottom like this:

    // global scripts
    
    // view scripts
    @RenderSection("scripts", false)
    // then finally trigger partial view scripts
    
    

    Then on my Partial View (at the bottom):

    
    

    Another solution is using a stack to push all your scripts, and call each one at the end. Other solution, as mentioned already, is RequireJS/AMD pattern, which works really well also.

提交回复
热议问题