【问题标题】:Optional section was not defined error in nested layout pages嵌套布局页面中未定义可选部分错误
【发布时间】:2021-09-08 21:19:41
【问题描述】:

我有一个 _Layout.cshtml 文件,其中包含以下行。

@RenderSection("Scripts", required: false)

然后我有一个 StorageLayout.cshtml 文件,将 _Layout.cshtml 指定为布局文件。 StorageLayout.cshtml 定义了MainMenu 部分并包含@RenderBody()

但是我使用 StorageLayout.cshtml 作为布局文件的页面给了我一个错误:

InvalidOperationException:以下部分已定义但尚未由位于“/Pages/Shared/_StorageLayout.cshtml”的页面呈现:“脚本”。要忽略未渲染的部分,请调用 IgnoreSection("sectionName")。

我不确定我是否理解这一点。 Scripts 部分明确不是必需的,那么为什么会出错?而且,就此而言,在嵌套布局文件中实现此部分的正确方法是什么?

【问题讨论】:

    标签: c# asp.net asp.net-core razor-pages asp.net5


    【解决方案1】:

    required设置为false,表示section是可选的。如果section不是可选的,每一个引用布局页面的内容页面都必须使用@section指令来定义section并提供内容:-

    @section Scripts{
        // content here
    }
    

    在某些情况下,您可能希望将某个部分设为可选,但您希望在内容页面没有为该部分提供任何内容的情况下提供一些默认内容。您可以为此使用IsSectionDefined 方法:-

    @if(IsSectionDefined("OptionalSection"))
    {
        @RenderSection("OptionalSection")
    }
    else
    {
        // default content
    }
    

    主布局中定义的任何部分也应该在子布局中重新定义:-

    _MasterLayout.cshtml

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="utf-8" />
            <title></title>
            <link href="/css/site.css" rel="stylesheet" type="text/css" />
        </head>
        <body>
            @RenderBody()
            @RenderSection("scripts", required:false)
        </body>
    </html>
    

    _ChildLayout.cshtml

    @{
        Layout = "/_MasterLayout";
    }
    <div class="main-content-two-col">
    @RenderBody()
    </div>
    @section scripts {
      @RenderSection("scripts", required: false)
    }
    

    我认为这将有助于解决您的问题。

    【讨论】:

    • 谢谢,但正如我在问题中解释的那样,Layout.cshtml 确实 包含@RenderSection("scripts", required: false)。此外,如前所述,required 设置为 false
    • @JonathanWood 我已经看到了。实际上,我试图澄清这一点。我认为您在 StorageLayout.cshtml 中缺少 @section scripts { @RenderSection("scripts", required: false) }
    • 是的,我要测试一下。我只是被你回答中的第一句话打断了,因为这显然与我的问题无关。
    • @JonathanWood 现在我通过删除 _Layout.cshtml 东西更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-26
    • 2016-11-09
    • 2012-07-30
    • 1970-01-01
    • 2015-01-17
    相关资源
    最近更新 更多