HI WELCOME TO Sirees

Part 50 - Detect errors in views at compile time

Leave a Comment
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 PropertyGroupMvcBuildViews 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.

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.