我正在使用 Razor View 层次结构设置我的 ASP.NET Core 站点,如下所示:
_Layout
_PanelLayout
Index
所以,我有这些文件:
_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>
当我运行返回 Index
View 的 Controller 操作时,出现错误:
InvalidOperationException: The following sections have been defined but have not been rendered by the page at '_PanelLayout.cshtml': 'scripts'.
为什么 Razor 不接受 Index 的祖父 View 正在呈现“脚本”部分这一事实?如果我删除该部分,布局工作正常,所以唯一的问题是这个部分渲染没有传递到祖 parent 布局。是否有解决此问题的方法仍然允许我决定在祖父布局 ('_Layout') 而不是父布局 ('_PanelLayout') 上呈现“脚本”部分的位置?
最佳答案
父布局中的任何部分都必须在子布局中重新定义,否则它们在继承链的下游将不可用。换句话说,在 _PanelLayout.cshtml
中你需要添加:
@section scripts
{
@RenderSection("scripts", required: false)
}
这为引用此布局 (RenderSection
) 的下一级布局或 View 提供了一个 Hook ,然后将其输出填充到 _Layout.cshtml
中的部分。
关于c# - 为什么我的 Razor 'RenderSection' 没有被孙 View 继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57959894/