Validation Context is always NULL?

依然范特西╮ 提交于 2019-12-11 04:09:29

问题


I have custom validation attribute such as this:

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

In usage like this:

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

My question is: why is it that inside MyCustomAttribute, within the IsValid method, validationContext is always NULL? Is there anything special I need to set to get it not to be NULL?


回答1:


if you use

ValidationResult IsValid(object value, ValidationContext validationContext)

to check if data is valid you have to use

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

instead of

 v.IsValid(propertyValue)


来源:https://stackoverflow.com/questions/5408658/validation-context-is-always-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!