MVC 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.
}
其中@section是Razor中的关键字

WebPageBase中的Section方法

WebPageBase充当表示 ASP.NET Razor 页的类的基类,即针对Razor页进行解析。主要的Section方法有:

//在布局页中(_Layout.cshtml),将呈现指定部分的内容。
public HelperResult RenderSection(string name);
public HelperResult RenderSection(string name, bool required);

//在布局页中,将呈现不在指定部分中的内容页部分。
public HelperResult RenderBody();
//该值指示是否在页中定义了指定部分
public bool IsSectionDefined(string name);

 

总结

  1. 从设计模式的角度来说,section的实现采用了模板方法(Template Method);
  2. 同Web Form对比的话,很像PlaceHolder,用于先占位,后替换
  3. 更加广一点来说,与String.Format() 的思维是一致的;
  4. 当然,Razor引擎一直想表达的就是这种思想,只不过section偏向将HTML当做一个子部分(partial)。
posted @ 2014-06-07 10:46  _DN  阅读(959)  评论(2编辑  收藏  举报