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

后端 未结 24 1911
无人共我
无人共我 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 07:00

    There is a way to insert sections in partial views, though it's not pretty. You need to have access to two variables from the parent View. Since part of your partial view's very purpose is to create that section, it makes sense to require these variables.

    Here's what it looks like to insert a section in the partial view:

    @model KeyValuePair
    @{
        Model.Key.DefineSection("SectionNameGoesHere", () =>
        {
            Model.Value.ViewContext.Writer.Write("Test");
        });
    }
    

    And in the page inserting the partial view...

    @Html.Partial(new KeyValuePair(this, Html))
    

    You can also use this technique to define the contents of a section programmatically in any class.

    Enjoy!

提交回复
热议问题