Compile Views with your MVC project

C

Most ASP.NET developers will use Visual Studio to build their projects. The program has evolved quite a bit over the past few years. Including excellent features like Intellisense inside of ASP.NET MVC view files as well as some error detection in these, by default, not compiled elements. However, when ViewBag variables are used or other run-time specific elements, Visual Studio is unable to determine potential errors in these view files. Have no fear though; there is a nice and simple solution to help solve this problem!

As I mentioned above, by default, views inside of your MVC project are not compiled until run-time. This can lead to some unexpected errors, such as data-type mismatches or null referenced variables, and of course any other unforeseen error. By making a simple change to your MVC project, you can tell Visual Studio to compile your views when the project is built, helping to avoid these errors.

MvcBuildViews Setting

To enable this feature, you will need to edit your csproj file in a text editor. Once the file is opened, search the file for the XML tag of MvcBuildViews. By default this value is set to false. Change the value to true and reload your project inside of Visual Studio.

If the XML tag does not already exist, it should be added as follows inside of the parent PropertyGroup XML tag:

[code]
<PropertyGroup>
<MvcBuildViews>true</MvcBuildViews>
</PropertyGroup>
[/code]

Now, when Visual Studio builds your project, if you have errors inside of your views they will be reported by the compiler.

It is important to note that this will add some additional overhead to your build process because each view must be compiled.

By altering or adding a new XML tag, MvcBuildViews, and setting it to true, your MVC application will compile your views during the build process enabling you to find potential run-time errors that would have been caused before your application is deployed. Once again, this will slow down your build process; however, the potential time saving of debugging an odd run-time error will definitely out weigh it in the long run!

About the author

By Jamie

My Books