嵌套布局页面中的可选部分未定义错误

Optional section was not defined error in nested layout pages

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

@RenderSection("Scripts", required: false)

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

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

InvalidOperationException: The following sections have been defined but have not been rendered by the page at '/Pages/Shared/_StorageLayout.cshtml': 'Scripts'. To ignore an unrendered section call IgnoreSection("sectionName").

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

required设置为false,表示section是optional.Ifsection不是可选的,每一个引用布局页的内容页都必须使用@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)
}

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