views:

99

answers:

2

Hi, 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.

A: 

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.

Nathan Taylor
Yes, I've heard of it. And it doesn't work no matter where I place _init.cshtml... How come?BTW Thank you very much for the link, it'll definitely help me in the future!
Darmak
Looking at the book again I see it says to put _init.cshtml, _start.cshtml, and _end.cshtml in the root directory of your website. Much like the Global.asax would be.
Nathan Taylor
`_init.cshtml` do not work in MVC 3 Preview 1 so you cannot follow that pattern. However, this will be supported in future releases.
marcind
Thanks, at least I know in future it'll (probably) work :)
Darmak
@marcind Where did you find this out, may I ask?
Nathan Taylor
I work on the ASP.NET team at Microsoft.
marcind
Well that seems like a reliable source of information to me =D
Nathan Taylor
Also, there's no such thing as an _end.cshtml file.
Eilon
+2  A: 

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.
marcind