I like the compiler to catch as many errors as possible before I start debugging or release my application. This also applies to code nuggets in ASP.NET MVC views, especially since these are not easily unit-testable. But views are not validated at compilation, at least not when using the standard settings for ASP.NET MVC projects.
Tools like Resharper can notify you of syntax errors within your views, but you can still build the project and not get a single error. Instead, your application will crash when trying to evaluate the buggy view.
Fortunately you can easily make Visual Studio compile your views along with the rest of your code. The only downside is that your project will build a bit slower, but if this bothers you during development you can also enable this feature on a per configuration basis. For example you may want to compile your views in Release mode, but not in your Debug configuration , so you have the extra safety of compile-time view checking before releasing a new version, but you still get lightning-fast compilation times while developing.
Please proceed as follows to turn on compile time view compilation:
- Open your .csproject or .vbproject file in a text editor of your choice. It’s just a simple xml file, which is why any editor will do fine.
- Locate the <PropertyGroup> element that belongs to the configuration you would like to alter.
- Within this PropertyGroup, add an additional element with “true” as its text value.
For example, this will turn on view compilation in my project’s Release configuration:
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <MvcBuildViews>true</MvcBuildViews> ...
That’s it! The next time one of your views has compile-time errors, these will be reported when building your application.
One last thing: You need to repeat this procedure for all configurations you might create in the future if you want your views to be checked in those configurations as well. Even if you tell Visual Studio to copy settings from an existing configuration where this tag is already set to true, the MvcBuildViews tag is not copied by Visual Studio.
Edit: As some readers pointed out, your project’s compilation time will increase after turning on view compilation. For this reason, I have recently switched it off for the debug configuration of my current project. However, compile-time view compilation is still tremendously useful before releasing a new version. Or perhaps even before submitting a new revision to your source control server. It can catch a lot of different errors this way, especially if you are using the new ASP.NET MVC strongly typed Html helpers.