Compile Time Error Checking in MVC 5

Before enabling that functionality first let's look at an example. 

In Visual Studio I have a MVC application in which all the views are strongly-typed.

The following is an image of an Index view.



Now as we all know there are several advantages to creating a strongly-typed view. But what will happen if I still misspell any of the field names?

Let's say there is a property “Gender” in our Model. Now what will happen if I type Genders instead of Gender?

  1. <td>  
  2.    @Html.DisplayFor(modelItem => item.Genders)  
  3. </td>  
But the actual name of this above field is Gender not Genders.

Build the application.

Build succeeded.

Run the application.



Look at the output we got. Our application throws an exception at line 49. The reason for this exception is that our application does not contain a definition for Genders. Even after creating a strongly-typed view we were not able to identify the error.

So, is there any way to identify these errors at compile time?

Absolutely.

By default the compiler error checking in MVC views is disabled.

If you want to enable it then all you need to do is open the current MVC project you are working on.

Look for a Visual C# Project file.



Open this file in any text editor like Notepad.

Look for <MvcBuildViews>false</MvcBuildViews>.

The value is false that by default restricts the compile-time error checking. Switch this to true and save the file.

Click on the Reload button.



Build the application.

build

So, now we have successfully enabled compile-time error checking.

Rename that property back to Gender and run the application.



I hope you like this article and find it helpful.

Thank you.


Similar Articles