2011-03-23 58 views
2

我有自定义验证属性像这样:验证上下文始终为NULL?

public class MyCustomAttribute : ValidationAttribute { 
    protected override ValidationResult IsValid(object value, ValidationContext validationContext) { 
     if ((int)value == 100) { 
      // do some checking to validate & return ValidationResult accordingly 

     } else return ValidationResult.Success; 
    } 
} 

在使用这样的:

[DisplayName("My Custom Property")] 
    [MyCustom(ErrorMessage = "ERROR!!!")] 
    public int? MyCustomProperty { get; set; } 

我的问题是:为什么是这里面MyCustomAttribute,该IsValid的方法中,validationContext始终是NULL ?有什么特别的我需要设置它不是NULL?

+5

我知道你的状态,你是,但我的理解是这是一个MVC 3.0功能。你确定你在使用MVC 3.0? – 2011-03-23 16:46:50

+0

默认情况下,您不需要做任何特殊的事情就可以使其发挥作用。 – Buildstarted 2011-03-23 17:01:23

+0

好的 - 由于某种奇怪的原因,它回复到2.0的参考(而不是坚持3.0参考)。我现在使用MVC 3.0(按预期)工作。 *叹。 – 2011-03-23 17:41:13

回答

3

如果使用

ValidationResult IsValid(object value, ValidationContext validationContext) 

检查数据是否是有效的,你必须使用

v.GetValidationResult(propertyValue,new ValidationContext(this))!= ValidationResult.Success 

,而不是

v.IsValid(propertyValue)