Asp.Net MVC 3 Areas and _ViewStart.cshtml Scope

I came across a problem today (or should I say misunderstanding) with MVC 3 (RC) and the _ViewStart.cshtml file.

In case you haven’t used these yet, the _ViewStart.cshtml is there to make it easy (and DRY) to apply the same layout file across all your views. The problem is that when you start to use areas, you might find your layout is not applied to the views inside your areas. You could copy your view start file into the view directories for your areas, but that’s not very DRY is it? It’ll become unmaintainable after a while.

The key thing to note is that, in fact, _viewstart.cshtml files have scope, and they affect all the views which are in the same directory or below the location of the file. By default, and in all the tutorials, blog posts and examples that I’ve seen, _viewstart.cshtml is always created in the Views folder in the root of the site, thus having an impact on the views inside that file.

If you want a wider scope so that it affects your area views as well, simply move _viewstart.cshtml into the root of your site, and the problem will be solved.

Similarly if you want to apply a different layout to all of your areas, but maintain the default one for non-area views, create another _viewstart.cshtml file inside the root of your /areas directory, and all your area views will maintain that layout.