加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – 如何手动调用ValidationAttributes? (DataAnnotatio

发布时间:2020-12-16 07:09:09 所属栏目:asp.Net 来源:网络整理
导读:我们需要在一些逻辑中迭代模型的属性以自动绑定属性,并希望扩展功能以在C#4.0中包含新的数据注释. 目前,我基本上遍历所有ValidationAttribute实例中的每个属性加载并尝试使用Validate / IsValid函数进行验证,但这似乎对我没有用. 作为一个例子,我有一个模型,
我们需要在一些逻辑中迭代模型的属性以自动绑定属性,并希望扩展功能以在C#4.0中包含新的数据注释.

目前,我基本上遍历所有ValidationAttribute实例中的每个属性加载并尝试使用Validate / IsValid函数进行验证,但这似乎对我没有用.

作为一个例子,我有一个模型,如:

public class HobbyModel
{
    [Required(AllowEmptyStrings = false,ErrorMessage = "Do not allow empty strings")]
    [DisplayName("Hobby")]
    [DataType(DataType.Text)]
    public string Hobby
    {
        get;
        set;
    }
}

检查属性的代码是:

object[] attributes = propertyInfo.GetCustomAttributes(true);
TypeConverter typeConverter =
TypeDescriptor.GetConverter(typeof(ValidationAttribute));

bool isValid = false;
foreach (object attr in attributes)
{
   ValidationAttribute attrib = attr as ValidationAttribute;

   if (attrib != null)
   {
     attrib.Validate(obj,propertyInfo.Name);
   }
}

我调试了代码,模型确实有3个属性,其中2个是从ValidationAttribute派生的,但是当代码通过Validate函数(带有空值或空值)时,它会按预期抛出异常.

我期待我做一些愚蠢的事情,所以我想知道是否有人使用过这个功能并且可以提供帮助.

提前致谢,
杰米

解决方法

这是因为您将源对象传递给 Validate方法,而不是属性值.以下更有可能按预期工作(尽管显然不适用于索引属性):

attrib.Validate(propertyInfo.GetValue(obj,null),propertyInfo.Name);

不过,你肯定会更容易using the Validator class作为Steven suggested.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读