【问题标题】:xVal, DataAnnotations on the entire classxVal,整个类的DataAnnotations
【发布时间】:2009-08-28 16:49:43
【问题描述】:

我对一个对象进行了完整的验证,并且正在尝试找出处理它的最佳方法。

给定以下类:

public class LetterResponse {
 public Guid Id {get;set;}
 public bool SendBlankCart {get;set;}
 public string ToName {get;set;}
 public string ToAddress {get;set;}
}

我想使用 dataannotation 和 xval 来在持久化类之前对其进行验证,但我的验证很复杂,需要多个属性。

伪:

if SendBlankCart {
 - no validation on ToName, ToAddress 
} else {
 ToName - required.
 ToAddress - required. 
}

我想这样注释:

[LetterResponseValidator]
public class LetterResponse {
 public Guid Id {get;set;}
 public bool SendBlankCart {get;set;}
 public string ToName {get;set;}
 public string ToAddress {get;set;}
}

并有这样的验证规则:

public class LetterResponseValidator : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            if (value.GetType() == typeof(LetterResponse))
            {
                var letterResponse = (letterResponse) value;
                if (letterResponse.SendBlankCard)
                {
                    return true;
                } else
                {
                    if (string.IsNullOrEmpty(letterResponse.FromDisplayName) || string.IsNullOrEmpty(letterResponse.ToAddress1))
                    {
                        return false;
                    }
                    return true;
                }

            }
            return false;
        }
    }

我希望该参数是我的 LetterResponse 类的实例,但它从未在我的验证运行程序上被调用?

有谁知道如何处理这个问题?

谢谢,

哈尔

【问题讨论】:

    标签: c# asp.net-mvc data-annotations xval


    【解决方案1】:

    我认为这与您拥有类级验证器这一事实无关。要排除任何连接,请尝试将虚拟所需验证器应用于“ToName”并查看是否调用了验证器。

    如果它被调用,请告诉我,如果不是,那么您应该检查您是否在 Global.asax.cs 文件中使用 DataAnnotationsModelBinder 覆盖了您的标准模型绑定器:

    ModelBinders.Binders.DefaultBinder = new DataAnnotationsModelBinder();
    

    有关此演示项目的更多详细信息,请阅读blog article about client-side validation

    【讨论】:

    • 是的 - 结果我的 DataAnnotation 运行器方法只检查属性,而不是类级别的属性。谢谢,哈尔
    • 你知道我在哪里可以找到与 System.ComponentModel.DataAnnotations v 3.5 一起使用的 DataAnnotationsModelBinder
    • 除了我在上面链接的博客文章中描述的一个错误之外,常规版本确实适用于 .NET 3.5 版。本文还展示了如何修复该错误。
    猜你喜欢
    • 2011-12-01
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-04
    相关资源
    最近更新 更多