Currently we are programmatically setting the layout file to
use at the top of our Index.cshtml file. This is fine for cases where we
have some view-specific logic where the layout file will vary depending on the
specific view. But setting it this way can end up being redundant and
duplicative for most web applications – where either all of the views use the
same layout, or if they have different layouts (for example: for mobile devices
or localized sites) the logic for which layout to pick is common across all of
the views.
The good news is that Razor (starting with the ASP.NET MVC 3
Beta release) includes a new feature that enables us to remove the need to
explicitly set the Layout in each view – and instead allows us to define the
layout logic once for all views in the site – making our view files even
cleaner and more maintainable (and ensuring we keep to the DRY principle: Don’t
Repeat Yourself):
Starting with the ASP.NET MVC 3 Beta release, you can now
add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath
the \Views folder of your project:
The _ViewStart file can be used to define common view code
that you want to execute at the start of each View’s rendering. For
example, we could write code like below within our _ViewStart.cshtml file to
programmatically set the Layout property for each View to be the
SiteLayout.cshtml file by default:
Because this code executes at the start of each View, we no
longer need to explicitly set the Layout in any of our individual view files
(except if we wanted to override the default value above).
Important: Because the _ViewStart.cshtml allows us to write
code, we can optionally make our Layout selection logic richer than just a
basic property set. For example: we could vary the Layout template that
we use depending on what type of device is accessing the site – and have a
phone or tablet optimized layout for those devices, and a desktop optimized
layout for PCs/Laptops. Or if we were building a CMS system or common
shared app that is used across multiple customers we could select different
layouts to use depending on the customer (or their role) when accessing the site.
This enables a lot of UI flexibility. It also allows
you to more easily write view logic once, and avoid repeating it in multiple
places.
Note: You can also specify layouts within a Controller or an
Action Filter. So if you prefer to keep the layout selection logic there you
can do that as well.