Monday 17 March 2014

Compiling ASP.NET MVC Views

If you've ever worked in ASP.NET MVC then you may have noticed that the server-side code in your views (e.g. your Razor logic) is not compiled as part of the build process. By default, views are compiled at runtime which means that any syntax error in your server-side view code may annoyingly only manifest after you've built, deployed and requested for the view which contains the error.

Fortunately, you can instruct the compiler to include your views in the build process by using the project-level boolean property MvcBuildViews. Setting this property to true will ensure your ASP.NET MVC views are also included in the build process and any syntax errors are caught at compile time.

To set this property, open your ASP.NET MVC application's csproj file in your favourite text editor. Locate the MvcBuildViews element and set its inner value to true. If you already have the project open in Visual Studio, the IDE will automatically detect the file change and ask you to reload the project. Once reloaded, you'll have compile time safety for your views.

The only disadvantage to this that I've noticed so far is that your builds take a bit longer to complete, however I've found this negligible compared to finding the error at runtime and having to do a patch deployment to another environment!