整个类上的xVal,DataAnnotations [英] xVal, DataAnnotations on the entire class

查看:88
本文介绍了整个类上的xVal,DataAnnotations的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经对对象进行了完整的验证,正在尝试找出处理它的最佳方法.

I have a complete validation on an obeject and am trying to figure out the best way to handle it.

提供以下课程:

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

我想使用数据注释和xval来在持久化该类之前对其进行验证,但是我有复杂的验证,需要多个属性.

I want to use a dataannotation and xval in order to validate the class before I persist it, but I have complex validation that requires more than one property.

伪:

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;}
}

,并具有如下验证规则:

and have a validation rule like this:

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类的实例,但是它永远不会在验证运行程序上被调用?

I am expecting the parameter to be my instance of the LetterResponse class, but it never gets called on my validation runner?

有人知道处理这个的方法吗?

Does anyone know a way to handle this?

谢谢

Hal

推荐答案

我认为这与您拥有类级别的验证程序无关.要排除任何连接,请尝试将一个虚拟的必需验证器应用于"ToName",然后查看是否调用了该验证器.

I don't think this has to do with the fact that you have a class-level validator. To exclude any connection, try applying a dummy required validator to "ToName" and see if the validator is called or not.

如果正在调用它,那么让我知道,如果不是,那么您应该检查是否已用Global.asax.cs文件中的DataAnnotationsModelBinder覆盖了标准modelbinder:

If it is being called, then let me know, if it's not, then you should check if you have overriden your standard modelbinder with the DataAnnotationsModelBinder in your Global.asax.cs file:

ModelBinders.Binders.DefaultBinder = new DataAnnotationsModelBinder();

有关此示例程序以及可以正常运行的演示项目的更多详细信息,请阅读此

For more details on this and fully working demo project, read this blog article about client-side validation.

这篇关于整个类上的xVal,DataAnnotations的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆