MVC5的嵌套布局

我在这个主题上看了几篇post:

Razor嵌套布局与层叠部分

MVC 3 – 嵌套布局 – 部分不在区域中渲染

它似乎总是有问题的。 然而,他们都很老了,所以想知道事情是否已经改变。

基本上我有一个主布局,以及3种不同的主体模板,基于它是什么类型的页面。 例如:

_Layout.cshtml

       
@RenderBody();
@Html.Partial("_FooterPartial")
@Html.Partial("_ScriptInitPartial")

_LayoutForEdit.cshtml

 
@RenderBody()

现在,这在调用时渲染得很好。 几乎。

部分的呈现必须在它看起来的子布局中。 如果我尝试将面包屑放在_Layout.cshtml ,它将失败,因为_LayoutForEdit.cshtml从未呈现它。 我怎样才能解决这个问题?

The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_LayoutForEdit.cshtml": "breadcrumbs".

我知道这是一个老问题。 无论如何,我想我会分享这个,以防其他人遇到这个(就像我一样)。

布局的底部,您可以定义一个与父布局中的部分同名的部分。 在本节的内部,您只需添加一个@RenderSection ,再次指定与之前相同的名称。 一旦到位,您基本上将子布局从页面“绕过”内容,直到其父布局:

 @section breadcrumbs { @RenderSection("breadcrumbs", true) } 

不确定你是否还需要帮助,但无论如何我都会回答。

RenderSection方法根据MSDN文档采用以下参数:

public HelperResult RenderSection( string name, bool required )

 Parameters name Type: System.String The section to render. required Type: System.Boolean true to specify that the section is required; otherwise, false. 

将通话更改为:

@RenderSection(“breadcrumbs”,false);

如果“required”参数部分为false,则如果视图未包含该部分,则不会给出错误。