標籤:.net mvc4
Mvc4的Razor視圖引擎還提供了@RenderSection
我的理解:@RenderSection在主版頁面中佔個位,然後讓使用此主版頁面的子頁自己去呈現他們的Section。
在主版頁面_Layout.cshtml中定義@RenderSection("Section名")
<body> <div id="header">@{Html.RenderAction("Menu", "Global");}</div> <div id="sideBar"> @RenderSection("SubMenu") </div> <div id="container">@RenderBody()</div> <div id="footer">@{Html.RenderAction("Footer", "Global");}</div></body>
添加一個About.cshtml,使用_Layout.cshtml做主版頁面
然後就可以在About.cshtml中定義"SubMenu"要呈現的內容
@{ ViewBag.Title = "About"; } @section SubMenu{ Hello This is a section implement in About View. }
這裡我在About.cshtml中實現了SubMenu,運行結果
但是當如果使用了_Layout.cshtml做主版頁面的頁沒有實現Section的話,
譬如我建立的Index.cshtml沒有實現@section SubMenu{...},就會拋出異常
這是因為我在_Layout.cshtml中使用的是@RenderSection("SubMenu")他要求所有子頁都要實現,
可以使用它的另外一個重載@RenderSection("SubMenu",false),第二個參數代表它不是必須的,就不會拋出異常。
還有,當我在主版頁面中定義了@RenderSection("SubMenu",false)的時候,我希望當所有子頁都沒有實現這個Section
的時候,主版頁面可以有自己的呈現內容,就可以用
<div id="sideBar"> @if (IsSectionDefined("SubMenu")) { @RenderSection("SubMenu", false) } else { <p>SubMenu Section is not defined!</p> } </div>這樣當沒有任何頁面呈現Section的時候,就會預設顯示定義的內容。
-----------------------------------------------------------------------------------
還有一種比較靈活的方法,通過擴充方法來實現
public static class Utility { public static HelperResult RenderSection(this WebPageBase page, string sectionName, Func<object, HelperResult> defaultContent) { if (page.IsSectionDefined(sectionName)) { return page.RenderSection(sectionName); } else { return defaultContent(null); } } }在主版頁面中
@this.RenderSection("SubMenu", @<div>default section content</div>)OK了!沒有呈現Section時,就預設顯示
<div>default section content</div>
.
MVC4 Razor @RenderSection - 主版頁面設定