代码改变世界

Asp.Net Razor中的Consistent Layout

2014-11-07 22:25  昏晓  阅读(261)  评论(0编辑  收藏  举报

有意义的参考:http://www.asp.net/web-pages/tutorials/working-with-pages/3-creating-a-consistent-look

Asp.net是怎样解决Consistent Layout问题的?是通过引入以下几个概念并提供相应的机制解决的:

  • Content Blocks,内容块,是包含html内容的文件,可以“插入”到其他页面中,一般不能直接访问,类似于Web Form中用户控件的概念;
  • Layout Pages,布局页面,是包含html内容的页面,可以在其中“插入”其他页面,也就是其内容可被“被插入的页面”共享,类似于Web Form中Master Page的概念;
  • Content Page,一般页面,可在其中使用RenderPage("content blcok文件路径")“插入”Content Block,可以使用@Layout="Layout page路径"引用Layout Page(如果Content Page页面同级或上级文件夹中存在_ViewStart.cshtml页面,则Content Page会继承该页面,该页面中一般会使用@Layout指令引用Layout页面),该页面在Layout Page页面出现的位置即Layout Page页面中RenderBody(Layout Page中只能定义一个RenderBody方法)方法出现的位置;
  • PartialView:

以上是MVC Layout机制的几个概念,在这几个概念中,Content Page是出于主动位置的,也就是说Content Page可以决定引用还是不引用、引用哪个Layout Page,Content Page(和Layout Page)可以决定是否定义Content Block,以及引用哪个Content Block。这些概念的应用依赖于以下方法:

  • RenderPage方法用于将Content Block"插入"到的其他页面,在其他页面中希望插入Content Block的位置调用RenderPage("content block文件路径")方法;
  • RenderBody方法用于在Layout pages中定义Content Page的位置;
  • Layout Pages页面中除了可以定义静态的被其他页面共享的内容之外,还可以预定义一些区域,其内容可以由引用该Layout Page的Content Page页面自行定义。方法是:在Layout Page页面通过调用RenderSection定义此由Content Page页面实现的区域,每个区域都有一个唯一的名称,通过在Content Page中使用@Section来定义该区域的具体内容。举例如下:
     1 在Layout page 中使用:
     2 @RenderSection("header", required: false)
     3 或者:
     4 @if (IsSectionDefined("header")) {
     5     @RenderSection("header")
     6 }
     7 
     8 在Content Page中:
     9 @section header {
    10     <div id="header">
    11         Creating a Consistent Look
    12     </div>
    13 }
    View Code

    一般来说,这种方式的使用场景可能不太多。

  • Content Page的PageData属性(Dictionary类型),用于在Content Blocks和Layout Pages之间共享数据。可参考上面链接中的“Passing Data to Layout Pages”部分。

以上方法中,无论是作为Content Blocks还是Layout Page,都是静态页面,也就是这些页面是预先定义好的,而非由Content Page对应的Action生成的(最多是该通过ViewBag传递动态数据),而非由另一个Action生成,通过以下方法,可以在页面中调用另外一个Action方法,从而生成该页面的部分内容:

  1. Html.Action:executes a separate controller action and displays the results. Action offers more fl exibility and re-use because the controller action can build a different model and make use of a separate controller context.
  2. Html.RenderAction: Html.RenderAction 与 Html.Action相同,但Html.RenderAction writes directly to the response (which can bring a slight efficiency gain).

这基本上就是全部的MVC Layout的概念了。

另外顺便说一下几个Rendering Helper的用法: