我有以下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
进行比较,以确保它们相等。我怎么能做到这一点?
答案 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;
}
}