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

Part 84 - Compare attribute in asp.net mvc

Suggested Videos 
Part 81 - Range attribute
Part 82 - Creating custom validation attribute
Part 83 - RegularExpression attribute



Compare attribute is used to compare 2 properties of a model. Comparing email addresses and passwords is the common use case of Compare attribute. Let's understand using Compare attribute with an example. We will be continuing with the example, that we discussed in Part 83.



To ensure that the user has typed the correct email, let's include "Confirm Email" field on the "Edit" view. To achieve this, add "ConfirmEmail" property in "Employee" class in Employee.cs class file that is present in "Models" folder. 
public partial class Employee
{
    public string ConfirmEmail { get; set; }
}

At this point you may get this question. Why are we not adding this property to EmployeeMetaData class. This is because EmployeeMetaData class, is used to associate metadata for the properties that are already present in the auto-generated Employee class. The auto-generated Employee class is present in SampleDataModel.Designer.cs file in Models folder. ConfirmEmail property does not exist in auto-generated Employee class. It is a new property that we want to add to Employee model class. ConfirmEmail property is going to be used only for validation. We will not be saving the value of this property to the database table. We will be stroing Emial property value to the database.

Build the solution, so that the Employee class is compiled.

Copy and paste the following 2 div tags, to add ConfirmEmail field to the Edit View.
<div class="editor-label">
    @Html.LabelFor(model => model.ConfirmEmail)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.ConfirmEmail)
    @Html.ValidationMessageFor(model => model.ConfirmEmail)
</div>

Finally, decorate ConfirmEmail property in Employee class with Compare attribute. Most of the validation attributes are present in System.ComponentModel.DataAnnotations namespace, but Compare attribute is present in System.Web.Mvc namespace.
public partial class Employee
{
    [Compare("Email")]
    public string ConfirmEmail { get; set; }
}

At this point, this confirm attribute will ensure Email and ConfirmEmail properties have the same values. If they don't, then a validation error message is displayed.

No comments:

Post a Comment

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.