MVC4 Razor @RenderSection - 主版頁面設定

來源:互聯網
上載者:User

標籤:.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 - 主版頁面設定

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.