c# - 为什么我的 Razor 'RenderSection' 没有被孙 View 继承?

标签 c# asp.net-mvc asp.net-core razor templating

我正在使用 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/

相关文章:

asp.net-mvc - 如何在 ASP.NET Core 6 MVC 应用程序中动态添加 Controller

asp.net-core - Asp.Net Core Identity - 使用角色和缓存授权属性?

reactjs - 如何在 ASP.NET Core 3 React 应用程序的 index.html 中从服务器注入(inject)数据

c# - 如何添加 Docker 选项以从 VS2022 运行 .NET Core 项目

c# - 如何从 Entity Framework 上的匿名查询更改数据

c# - 使用自定义功能覆盖 MVC 模型显示名称注释

javascript - 如何使用 JavaScript 加密然后使用 C# 解密

c# - 如何使用基于声明的授权保护 asp.net core 2.1 中的静态文件夹

c# - System.Security.Cryptography.RNGCryptoServiceProvider 是否投诉 FIPS 140-2?

c# - 基于域和主机名的 ASP.NET MVC 路由