2

我的模型包含一些成员:

public class Address
{
   public Street { get; set;}
   public City { get; set; }
   public PostalCode { get; set; }
}

现在我已经像这样覆盖了我ValidationAttribute的 withIsValid方法:

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
    var input = value as Address;

    if (string.IsNullOrEmpty(input.City))
        return new ValidationResult("City is required);

    if (!string.IsNullOrEmpty(input.PostalCode))
        if (string.IsNullOrEmpty(input.Street))
            return new ValidationResult("Stret is required");

    return ValidationResult.Success;
}

问题是:

验证后,我的模型状态仅将模型错误添加到整个 Adress 成员,但我需要将其添加到指定成员,如城市或街道。

对此的任何帮助将不胜感激......谢谢!

4

2 回答 2

4

你可以添加 memberNames !

return new ValidationResult("City is required", new string[] { "City", "Street" });

编辑: 我已经测试并找到了解决方案:System.ComponentModel.IDataErrorInfo !这在 javascript 客户端上不起作用,但是在提交结果时我们尝试了 :) 所以请继续使用 ValidationResult 和 memberNames 和:

public class myModel : System.ComponentModel.IDataErrorInfo
    {

        private Dictionary<string, List<ValidationResult>> errors;
        private bool IsValidated = false;

        private void Validate()
        {
            errors = new Dictionary<string, List<ValidationResult>>();
            List<ValidationResult> lst = new List<ValidationResult>();
            Validator.TryValidateObject(this, new ValidationContext(this, null, null), lst, true);
            lst.ForEach(vr =>
                {
                    foreach (var memberName in vr.MemberNames)
                        AddError(memberName, vr);
                });
            IsValidated = true;
        }
        private void AddError(string memberName, ValidationResult error)
        {
            if (!errors.ContainsKey(memberName))
                errors[memberName] = new List<ValidationResult>();
            errors[memberName].Add(error);
        }

        public string Error
        {
            get
            {
                if (!IsValidated)
                    Validate();

                return string.Join("\n", errors
                    .Where(kvp => kvp.Value.Any())
                    .Select(kvp => kvp.Key + " : " + string.Join(", ", kvp.Value.Select(err => err.ErrorMessage)))
                    );
            }
        }

        public string this[string columnName]
        {
            get
            {
                if (!IsValidated)
                    Validate();

                if (errors.ContainsKey(columnName))
                {
                    var value = errors[columnName];
                    return string.Join(", ", value.Select(err => err.ErrorMessage));
                }
                else
                    return null;
            }
        }

现在当前属性被标记为错误,并且 memberNames 也是!

:D

编辑 2

实际上,您可以保留简单的 DataAnnotations 来通知客户端,而在服务器端,您可以添加更复杂的业务验证:

public class myModel : IValidatableObject
{
      public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
      {

            if (string.IsNullOrEmpty(input.City))
                  yield return new ValidationResult("City is required",new string[]{"prop1","prop2"});
            if (!string.IsNullOrEmpty(input.PostalCode))
                  if (string.IsNullOrEmpty(input.Street))
                        yield return new ValidationResult("Stret is required");
      }

请注意,仅当 DataAnnotations 都有效时才调用Validate 方法!

于 2011-07-22T14:06:12.583 回答
1

你需要使用这个类的构造函数ValidationResult。例如

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
    var input = value as Address;

    if (string.IsNullOrEmpty(input.City))
        return new ValidationResult("City is required", new List<string>(){"City"});

    if (!string.IsNullOrEmpty(input.PostalCode))
        if (string.IsNullOrEmpty(input.Street))
            return new ValidationResult("Stret is required", new List<string>(){"Street"});

    return ValidationResult.Success;
}
于 2011-07-22T14:04:30.007 回答