Part 84 - Compare attribute in asp.net mvc

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 { getset; }
}

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 { getset; }
}

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. 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值