Compile Views with your MVC project Compile Views with your MVC project

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:


<PropertyGroup>
<MvcBuildViews>true</MvcBuildViews>
</PropertyGroup>

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!

Published on Mar 6, 2019

Tags: ASP.NET MVC and Web API Tutorial | c#

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.