如何手动调用ValidationAttributes? (DataAnnotations和ModelState)

时间:2010-12-13 08:05:51

标签: asp.net data-annotations asp.net-mvc-3 modelstate validationattribute

我们需要在一些逻辑中迭代模型的属性以自动绑定属性,并希望扩展功能以在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函数(带有空值或空值)时,它会按预期抛出异常。

我期待我做的事情很傻,所以我想知道是否有人使用过这个功能并且可能有所帮助。

提前致谢, 杰米

2 个答案:

答案 0 :(得分:4)

您确实使用System.ComponentModel.DataAnnotations.Validator类来验证对象。

答案 1 :(得分:3)

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

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

尽管如此,你肯定会更容易using the Validator class Steven suggested