1

标题说明了一切,但我会在这里添加一些背景知识。

直到最近,我一直在使用已经编写好的 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 PasswordDisplay属性指定。

我已经得到了这个工作,虽然不完全。以下实现(出于某种原因)解决了无法获取指定属性名称的问题,但我不确定为什么:

public class CompareWithDisplayNameAttribute : CompareAttribute
{
    public CompareWithDisplayNameAttribute(string otherProperty)
        : base(otherProperty)
    {
    }
}

现在,即使这可行,客户端验证也不起作用。我收到了另一个问题的答案,建议使用类似这样的东西

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CompareWithDisplayName), typeof(CompareAttributeAdapter))

在我的Global.asax,但是CompareAttributeAdapter实际上并不存在。

所以我在这里。我的Display自定义属性已正确使用该CompareWithDisplayName属性,但客户端验证完全缺失。

如何以最简洁的方式使客户端验证与此解决方案一起工作?

4

1 回答 1

3

如果您希望您的自定义比较属性与客户端验证一起使用,您将需要实现IClientValidatable. 您可以在GetValidationRules其中进行任何您可能希望的自定义​​验证。

例子

public class CompareWithDisplayNameAttribute : CompareAttribute, IClientValidatable
{
    public CompareWithDisplayNameAttribute(string otherProperty)
        : base(otherProperty)
    {
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
        ModelMetadata metadata, ControllerContext context)
    {
        // Custom validation goes here.
        yield return new ModelClientValidationRule();
    }
}
于 2013-08-27T16:55:19.360 回答