Reputation: 905
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.
Upvotes: 25
Views: 12741
Reputation: 2866
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.
Upvotes: 68
Reputation: 53183
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)
@inherits
directive in every view.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.Upvotes: 0
Reputation: 24606
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.
Upvotes: 2