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')?