Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Part 50 - Detect errors in views at compile time

Suggested Videos 
Part 47 - Displaying images in MVC
Part 48 - Custom html helpers in mvc
Part 49 - Html encoding in asp.net mvc

In this video, we will discuss, detecting errors in views at compile-time rather than at run-time.



The following code will display employee's FullName and Gender. Here we are working with a strongly typed view. Employee is the model class for this view. This class has got "FullName" and "Gender" properties. 
@model MVCDemo.Models.Employee
<fieldset>
    <legend>Employee</legend>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.FullName)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.FullName)
    </div>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.Gender)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Gender)
    </div>
</fieldset>



For example, if you mis-spell FullName property as shown below, and when you compile the project, you wouldn't get any compile time errors.
@Html.DisplayNameFor(model => model.FullName1)

You will only come to know, about the error when the page crashes at run-time. If you want to enable compile time error checking for views in MVC
1. Open MVC project file using a notepad. Project files have the extension of .csproj or .vbproj
2. Search for MvcBuildViews under PropertyGroup. MvcBuildViews is false by default. Turn this to true as shown below.
<MvcBuildViews>true</MvcBuildViews>
3. Save the changes.

If you now build the project, you should get compile time error.

Please Note: Pre-compiling views is different from compile-time error checking. We will discuss pre-compiling views in a later video session.

1 comment:

  1. in my case, i have to choose C# MvcDemo file not the MvcDemo.csproj file. thank you !!

    ReplyDelete

If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.