MVC5的嵌套布局

Tim*_*Tim 15 c# asp.net-mvc asp.net-mvc-5

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

Razor嵌套布局与层叠部分

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

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

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

_Layout.cshtml

<html lang="en">
    <head>
    </head>
    <body style="padding: 50px 0;">
        <header class="navbar navbar-default navbar-fixed-top" role="banner">
            @Html.Partial("_MenuPartial")
        </header>
        <ol class="breadcrumbs">
            @RenderSection("breadcrumbs", true);
        </ol>
        <section>
            @RenderBody();
        </section>
            <footer class="navbar navbar-default navbar-fixed-bottom">
            @Html.Partial("_FooterPartial")
        </footer>
        @Html.Partial("_ScriptInitPartial")
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

_LayoutForEdit.cshtml

<div class="panel panel-primary">
    <div class="panel-body">
        <div class="col-lg-2">
            <ul class="nav nav-pills nav-stacked">
                @RenderSection("tabs", true)
            </ul>
        </div>
        <div class="col-lg-10">
            <div class="tab-content">
                @RenderBody()
            </div>
        </div>
    </div>
    <div class="panel-footer">
        <button class="btn btn-primary" data-bind="enable: Entity.isValid, click: save">Save</button>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

现在,这在调用时呈现正常.几乎.

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

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

Dan*_*zzi 33

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

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

@section breadcrumbs {
    @RenderSection("breadcrumbs", true)
}
Run Code Online (Sandbox Code Playgroud)