如何通过数据注释比较这两个属性?

时间:2015-05-06 15:40:20

标签: asp.net-mvc validation asp.net-mvc-4 data-annotations

我有以下ViewModel:

public class RegistrationViewModel
{
    public Associate Associate { get; set; }

    public AssociateWeight AssociateWeight { get; set; }

    [DisplayName("Confirm Weight")]
    [Required(ErrorMessage = "Please enter a weight.")]
    [Compare("AssociateWeight.Weight", ErrorMessage = "Please enter identical weights.")]
    public decimal ConfirmWeight { get; set; }
}

属性AssociateWeight有一个名为Weight的属性,我想与ConfirmWeight进行比较,以确保它们相等。我怎么能做到这一点?

1 个答案:

答案 0 :(得分:0)

您可以通过自定义验证来实现此目的

<强>模型

[RegistrationValidation]
public class RegistrationViewModel
{
    public Associate Associate { get; set; }
    public AssociateWeight AssociateWeight { get; set; }
    [DisplayName("Confirm Weight")]
    [Required(ErrorMessage = "Please enter a weight.")]   
    public decimal ConfirmWeight { get; set; }
}

自定义验证

public class RegistrationValidation : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        RegistrationViewModel app = value as RegistrationViewModel;
        if (app.AssociateWeight.weight != app.ConfirmWeight)
            {
                ErrorMessage = "Please enter identical weights.";
                return false;
            }
        return true;
    }
}