Пользовательский атрибут ValidationAttribute, не отображаемый в элементе - PullRequest
1 голос
/ 25 ноября 2011

Я работаю над несколько унаследованным пахнущим проектом MVC2, в котором кто-то пытался сделать атрибут проверки ConfirmMustMatch. Я исправил это, используя PropertiesMustMatchAttribute , но он отображается только в ValidationSummary. Это очевидно, потому что ключ ModelStateError является пустой строкой. Итак, я искал метод с ValidationResult, где я могу дать имена членов. Итак, теперь атрибуты выглядят так, но ошибка по-прежнему переходит к ключу строки. Пустые, а не фактические члены!

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public sealed class PropertiesMustMatchAttribute : ValidationAttribute
{

    private const string _defaultErrorMessage = "'{0}' and '{1}' do not match.";
    private readonly object _typeId = new object();

    public PropertiesMustMatchAttribute(string originalProperty, string confirmProperty)
        : base(_defaultErrorMessage)
    {
        OriginalProperty = originalProperty;
        ConfirmProperty = confirmProperty;

    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
        object originalValue = properties.Find(OriginalProperty, true /* ignoreCase */).GetValue(value);
        object confirmValue = properties.Find(ConfirmProperty, true /* ignoreCase */).GetValue(value);
        if (Object.Equals(originalValue, confirmValue) == false)
            return new ValidationResult(ErrorMessage, new[] { OriginalProperty, ConfirmProperty });
        else return ValidationResult.Success;
    }

    public string ConfirmProperty { get; private set; }
    public string OriginalProperty { get; private set; }

    public override object TypeId
    {
        get
        {
            return _typeId;
        }
    }

    public override string FormatErrorMessage(string name)
    {
        return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
            OriginalProperty, ConfirmProperty);
    }

}
...