我有一个用于更改密码的 ViewModel,它使用 Compare DataAnnotation,如下所示:
[Display(Name = "New Password")]
public string New { get; set; }
[Compare("New")]
[Display(Name = "Confirm Password")]
public string ConfirmPassword { get; set; }
不幸的是,Compare 属性没有利用比较属性的 Display 属性。
错误信息显示为
'Confirm Password' and 'New' do not match.
您可以看到它使用了比较属性的 Display 属性,但没有使用比较属性的属性。
我还将指定我不想使用 ErrorMessage 参数,因为这样我将对属性名称进行硬编码,而不是简单地从现有属性中获取它。我希望尽可能保持此解决方案的最佳实践。
如何使 Compare 属性利用比较属性的 Display 属性?
请您参考如下方法:
我认为这可能是 Compare 属性的一些问题,因为您可以在其属性列表中看到 OtherDisplayName 属性,并且它正确地使用了它正在装饰的属性的显示名称(“确认密码”而不是“确认密码”)。
我发现的一种解决方法是简单地创建一个继承自 CompareAttribute 的新类,如下所示:
public class CompareWithDisplayName : CompareAttribute
{
public CompareWithDisplayName(string otherProperty) : base(otherProperty)
{
}
}
然后在您的属性(property)上使用它:
[Display(Name = "New Password")]
public string New { get; set; }
[Display(Name = "Confirm Password")]
[CompareWithDisplayName("New")]
public string ConfirmPassword { get; set; }
老实说,我不知道为什么会这样。这可能与反射或计算每个属性的显示属性的顺序有关。通过创建它的自定义版本,也许顺序会改变?不管怎样,这对我有用:)
编辑 2 抱歉,忘记添加客户端验证所需的额外部分,这已解释 here .您可以将其添加到您的 Global.asax.cs 文件中:
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CompareWithDisplayName), typeof(CompareAttributeAdapter))
或者在自定义属性上实现 IClientValidatable 接口(interface)。这两个都显示在链接中
