gpt4 book ai didi

c# - 验证上下文始终为 NULL?

转载 作者:行者123 更新时间:2023-11-30 22:40:02 24 4
gpt4 key购买 nike

我有这样的自定义验证属性:

    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 吗?

最佳答案

如果你使用

ValidationResult IsValid(object value, ValidationContext validationContext)

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

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

代替

 v.IsValid(propertyValue)

关于c# - 验证上下文始终为 NULL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5408658/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com