开发者

How to specify default LayoutPage in Razor in ASP.NET MVC 3 Preview 1?

I want to specify (in one place) a default layout page in Razor, so that I can开发者_如何转开发 delete this:

@{ LayoutPage = "~/Views/Shared/_Layout.cshtml"; }

from every .cshtml file I have. But I don't know how... Any ideas? I'm using Razor engine from ASP.NET MVC 3 Preview 1.


Create a "~/Views/_ViewStart.cshtml" page and the following inside:

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Note that you can write code in here, so it is possible to change your layout based on the type of device targeted, etc.

This is now created by default in an empty MVC3 project.

Source


It looks like the way to do this is by using a _init.cshtml file in the root of the view directory in which you would like a common page element (header). When the Razor view engine builds your page it looks for a few specific files automatically called _start.cshtml, _init.cshtml, and _end.cshtml; these files are loaded in respective order by the view engine for every request. Placing the LayoutPage definition, and/or other common initialization operations in these files will ensure they're run for all pages.

Note: I'm not sure if the effect is passed down into sub-directories as it wasn't clear from the documentation; you'll have to give it a try and find out.

There's quite a bit more detailed information on how to do this found in the Microsoft how-to book on building pages with Razor. I found the section Running Code Before and After Files in a Folder on page 169. Check this Microsoft download page for the full book as well as additional Razor samples.


There is no easy way to do this in MVC 3 Preview 1. This is a limitation of the preview bits that will be addressed in upcoming releases. Unfortunately _init.cshtml files do not work in this preview of MVC3 so you cannot follow the Web Pages pattern.

There are 2 ways I can think of to make it work (though neither is optimal)

  1. write your own page base class that derives from WebViewPage and sets the right Layout in the constructor... but in that case you would have to specify an @inherits directive in every view.
  2. set the layout override in your action method (using the View(string viewName, string masterName) override). You could write an intermediate controller base class that would have a helper method to save yourself the trouble of repeating the layout everywhere.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜