Jez
Jez

Reputation: 30063

Why does my Razor 'RenderSection' not get inherited by a grandchild view?

I'm setting up my ASP.NET Core site with a hierarchy of Razor views, which goes like this:

_Layout
    _PanelLayout
        Index

So, I have these files:


_ViewStart.cshtml

@{
    Layout = "_PanelLayout";
}

_PanelLayout.cshtml

@{
    Layout = "_Layout";
}
<div>Panel layout file</div>
@RenderBody()

_Layout.cshtml

<html><body>
    <div>Main layout file</div>
    @RenderBody()
    @RenderSection("scripts", required: false)
</body></html>

Index.cshtml

@section scripts {
    <script>
        // test script
    </script>
}
<div>Content view</div>

When I run a controller action that returns the Index view, I get the error:

InvalidOperationException: The following sections have been defined but have not been rendered by the page at '_PanelLayout.cshtml': 'scripts'.

Why doesn't Razor pick up the fact that the grandparent view of Index is rendering a 'scripts' section? If I remove the section, the layout works fine, so the only problem is this section rendering not carrying through to the grandparent layout. Is there a solution to this problem that still allows me to decide where I want to render the 'scripts' section on the grandparent layout ('_Layout') rather than the parent layout ('_PanelLayout')?

Upvotes: 3

Views: 1642

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239400

Any sections in parent layouts must be redefined in the child layouts or they will not be available further down the inheritance chain. In other words, in _PanelLayout.cshtml you need to add:

@section scripts
{
    @RenderSection("scripts", required: false)
}

This gives a hook to the next level of layout or view referencing this layout (RenderSection) and then stuffs the output of that into the section in _Layout.cshtml.

Upvotes: 8

Related Questions