Mvc3的Razor視圖引擎還提供了@RenderSection
我的理解:@RenderSection在母版頁中佔個位,然後讓使用此母版頁的子頁自己去呈現他們的Section。
在母版頁_Layout.cshtml中定義@RenderSection("Section名")
<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
的時候,母版頁可以有自己的呈現內容,就可以用
@if (IsSectionDefined("SubMenu"))
{
@RenderSection("SubMenu", false)
}
else
{
<p>SubMenu Section is not defined!</p>
}
</div>
這樣當沒有任何頁面呈現Section的時候,就會默認顯示定義的內容。