MVC Layout VS MVC Master Page

不羁的心 提交于 2019-11-30 06:21:28

You could use sections with Razor. Scott Gu blogged about them here: http://weblogs.asp.net/scottgu/archive/2010/12/30/asp-net-mvc-3-layouts-and-sections-with-razor.aspx

In your Layout you could define as many sections as you wish:

<div id="leftMenu">
    @RenderSection("LeftMenu", required: false)
</div>

which you could override in your views:

@section LeftMenu {
    <div>... here comes the left menu for this view ...</div>
}

You could also test whether a section has been defined in a view and if not provide some default content:

@if (IsSectionDefined("LeftMenu")) { 
    @RenderSection("LeftMenu")
}
else { 
    <div>Some default left menu</div>
}
Mauricio Gracia Gutierrez

Starting with MVC3, the razor view engine was introduced. At a high level, a view engine is basically what takes the view and renders the necessary HTML. Razor uses the _layout.cshtml file and it's own templating system that is similar to master pages. However, MVC3 and 4 have another view engine called WebForms View Engine and this does use master pages. If you look at MVC1 and MVC2 tutorials respectively, you'll see master pages. Prior to MVC3 there was only WebForms View Engine.

Now in terms of functionality, both are similar. Master pages allow you to define content place holders while Razor allows you to define sections. The one major difference between the two would be in how the page is rendered. Master pages render the page outside in, meaning first the master page, then the content place holders. Razor is, I believe, recursive and starts with the innermost sections and works it's way back out.

Check out this blog post for more information on razor layouts: http://weblogs.asp.net/scottgu/archive/2010/12/30/asp-net-mvc-3-layouts-and-sections-with-razor.aspx

In terms of which one is preferred, both view engines exist; but if you want to utilize the razor syntax - which I highly recommend - then you have to use the layout system. Razor doesn't allow you to use master pages.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!