2012-09-19 72 views
2

在剃鬚刀,我與在其中定義與代碼段示出一些默認的主頁,如果沒有值:如何製作嵌套的母版頁剃鬚刀部分未定義?

<html> 
<head><title>Title</title></head> 
<body> 
    @if (IsSectionDefined("optionalSection")) 
    { 
     @RenderSection("optionalSection", required: false) 
    } 
    else 
    { 
     <div>Some default content</div> 
    } 
</body> 
</html> 

我也有在此之上的嵌套主頁它創建了一個通通過部分定義:

@section optionalSection { 
    @RenderSection("optionalSection", required: false) 
} 

我遇到的問題是,當我使用此嵌套母版頁時,母版頁認爲該部分總是定義。這將永遠不會顯示其他部分。我考慮改變嵌套主節中的節的名稱並在主節點中檢查這個節的名稱,但是我們有一些嵌套的主節點,並且如果遵循這種模式,我覺得主節點會有不必要的爆炸。我該如何做這項工作?

回答

2

你可以寫一個自定義的擴展方法:

public static class SectionExtensions 
{ 
    public static HelperResult RedefineSection(
     this WebPageBase page, 
     string sectionName 
    ) 
    { 
     if (page.IsSectionDefined(sectionName)) 
     { 
      page.DefineSection(
       sectionName, 
       () => page.Write(page.RenderSection(sectionName)) 
      ); 
     } 
     return new HelperResult(_ => { }); 
    } 
} 

,然後你的嵌套佈局調用此擴展方法來重新定義段內:

@this.RedefineSection("optionalSection")