To follow better DRY (Don’t Repeat Yourself) principle Razor views support now defaults that are applied to all views in ASP.NET MVC web application. Default can be applied by special file so you have one place where everything common is defined. In this posting I will show you how defaults work and how to use them.
View start files
If you create new ASP.NET MVC 3 Beta web application you will find there file called _ViewStart.cshtml. In VB.NET projects this file is called _ViewStart.vbhtml.
By default this file is very short and simple containing only definition for layout page (ASPX synonym for layout page is master page). This page is run before the code of requested view is run.
_ViewStart.cshtml has also scope – it works for views that are located under the folder where _ViewStart.cshtml is. Views in other folders (by example views in other areas if you are using areas) are not affected by _ViewStart.cshtml in /Views/ folder.
Image on right shows how _ViewStart.cshtml is located in default internet application project. By example, it covers all views in Home and Shared folder but not views that have restricted access (_Layout.cshtml cannot be accessed directly).
Of course, we can add more functionality to _ViewStart.cshtml if we need but you have to be sure that this is something that cannot be easily done using layout pages and this is something that must be applied to views.