2014-01-09 26 views
10

我看到關於這一主題的幾個帖子嵌套式佈局:爲MVC5

Razor Nested Layouts with Cascading Sections

MVC 3 - Nested layouts - sections don't render in Areas

而且這似乎總是有問題的。然而,他們都很老,所以想知道事情是否發生了變化。

基本上我有一個總體佈局,並根據它是什麼樣的頁面的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> 

_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> 

調用時現在,這使得罰款。幾乎。

部分的渲染必須在子佈局看起來。如果我試圖把麪包屑在_Layout.cshtml,它會失敗,因爲_LayoutForEdit.cshtml從來沒有顯示它。我怎樣才能解決這個問題?

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

+0

我最好的解決方案至今,一直到所有的部分移動到模板,但這個原因複製。 – Tim

回答

24

我知道這是一個老問題。無論如何,如果有其他人遇到這種情況,我想我會分享這一點(就像我一樣)。

在您的子版式的底部,您可以定義一個與父佈局中的部分名稱相同的部分。在本節內部,您只需輸入@RenderSection,再次指定與以前相同的名稱。一旦到位,就基本上是有子佈局「搭橋」,從頁面的內容,最多其父佈局:

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

不知道,如果你還需要幫助,但我會回答反正。

有RenderSection方法根據 MSDN Documentation採用以下參數:

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( 「麪包屑」,假);

如果「所要求的」節參數爲假,它不會如果不是由視圖包含該部分給出一個錯誤。

+1

我不需要幫助了,這聽起來像你誤解了問題。我在身體中定義麪包屑,這是部分視圖的局部視圖,嵌套會遮擋正在檢測的部分。 – Tim

+0

@Tim他實際上正確地回答了你的問題。如果這不是你想要的,那麼你的問題是不正確的 – Leo