标签:
/Views/_ViewStart.cshtml 文件会在其他视图文档被加载之前被载入,代码如下:
1 @{ 2 Layout = "~/Views/Shared/_Layout.cshtml"; 3 }
标志主板页为_Layout.cshtml。_ViewStart.cshtml文件同样可以出现在Views子目录下,实现不同的控制器下预设载入不同的主版页面。_Layout.cshtml代码结构:
1 <header> 2 <div>...</div> 3 </header> 4 <div id="body"> 5 @RenderSection("featured", required: false) 6 <section class="content-wrapper main-content clear-fix"> 7 @RenderBody() 8 </section> 9 </div> 10 <footer> 11 <div>...</div> 12 </footer>
注意代码中的@RenderSection和@RenderBody,@RenderBody在Razor主版页面中可以视为“预设坑洞”,也就是说View视图会被填入到@RenderBody的位置。
@RenderSection在Razor主版页面中可以被视为“具名坑洞”,如果把required具名参数指定为true的话,那么所有载入这个主版页面的View页面都必须在@RenderSection中输出相应的内容,否则将产生异常。而“featured”就是坑洞的名字,因为required为false,所以不必填充该具名坑洞。MVC模板项目中Index.cshtml是这样填充的,如下:
1 @section featured { 2 <section class="featured"> 3 <div class="content-wrapper"> 4 <hgroup class="title"> 5 <h1>@ViewBag.Title.</h1> 6 <h2>@ViewBag.Message</h2> 7 </hgroup> 8 <p> 9 To learn more about ASP.NET MVC visit 10 <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>. 11 The page features <mark>videos, tutorials, and samples</mark> to help you get the most from ASP.NET MVC. 12 If you have any questions about ASP.NET MVC visit 13 <a href="http://forums.asp.net/1146.aspx/1?MVC" title="ASP.NET MVC Forum">our forums</a>. 14 </p> 15 </div> 16 </section> 17 }
Razor页面有固定的执行顺序,先执行View在执行Layout主版页面,因为View与Layout公用一个ViewDataDictionary实体,因此可以通过ViewBag将数据从View传递到Layout页面中,但反过来并不成立。
标签:
原文地址:http://www.cnblogs.com/SharpL/p/4596044.html