标题说明了一切,但我会在这里添加一些背景知识。
直到最近,我一直在使用已经编写好的 MVCCompareAttribute
来比较两个值,在本例中是密码及其确认。它工作得很好,除了这个属性不显示显示名称,由[Display(Name = "Name")]
被比较的属性的属性设置。
以下是正在比较的两个属性:
[Required]
[Display(Name = "New Password")]
public string New { get; set; }
[Compare("New")]
[Display(Name = "Confirm Password")]
public string ConfirmPassword { get; set; }
验证消息如下所示:
'Confirm Password' and 'New' do not match.
这行得通,但显然不如应有的那么好。New
应该读为,New Password
由Display
属性指定。
我已经得到了这个工作,虽然不完全。以下实现(出于某种原因)解决了无法获取指定属性名称的问题,但我不确定为什么:
public class CompareWithDisplayNameAttribute : CompareAttribute
{
public CompareWithDisplayNameAttribute(string otherProperty)
: base(otherProperty)
{
}
}
现在,即使这可行,客户端验证也不起作用。我收到了另一个问题的答案,建议使用类似这样的东西
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CompareWithDisplayName), typeof(CompareAttributeAdapter))
在我的Global.asax
,但是CompareAttributeAdapter
实际上并不存在。
所以我在这里。我的Display
自定义属性已正确使用该CompareWithDisplayName
属性,但客户端验证完全缺失。
如何以最简洁的方式使客户端验证与此解决方案一起工作?