如何手动调用ValidationAttributes? (DataAnnotations和ModelState中) [英] How to call ValidationAttributes manually? (DataAnnotations and ModelState)

查看:271
本文介绍了如何手动调用ValidationAttributes? (DataAnnotations和ModelState中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一些在我们的逻辑中必要通过模型来自动绑定属性的特性进行迭代,并要扩展的功能,包括C#4.0新dataannotations。

We have a need within some of our logic to iterate through the properties of a model to auto-bind properties and want to extend the functionality to include the new dataannotations in C# 4.0.

目前,我基本上遍历所有ValidationAttribute情况下,每个属性加载和尝试使用的验证/ IsValid的功能验证,但这似乎并不能为我工作。

At the moment, I basically iterate over each property loading in all ValidationAttribute instances and attempting to validate using the Validate/IsValid function, but this doesn't seem to be working for me.

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

As an example I have a model such as:

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

而code,检查的属性是:

And the code to check the attributes is:

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

我已经调试了code和模式确实有3个属性,其中2个是从ValidationAttribute来源,但是当code经过验证功能(用空或空值),它抛出预期的异常。

I've debugged the code and the model does have 3 attributes, 2 of which are derived from ValidationAttribute, but when the code passes through the Validate function (with a empty or null value) it does thrown an exception as expected.

我期待我做一些愚蠢的,所以我想知道是否有人使用此功能,并能有所帮助。

I'm expecting I'm doing something silly, so am wondering whether anyone has used this functionality and could help.

在此先感谢,
杰米

Thanks in advance, Jamie

推荐答案

这是因为你传递源对象的的 验证 方法,而不是属性值。如预期下更可能的工作(尽管显然不是索引属性):

This is because you are passing the source object to the Validate method, instead of the property value. The following is more likely to work as expected (though obviously not for indexed properties):

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

您肯定有一个更容易的时间<一个href=\"http://odeto$c$c.com/blogs/scott/archive/2011/06/29/manual-validation-with-data-annotations.aspx\"相对=nofollow>使用Validator类作为史蒂芬建议,虽然。

You would certainly have an easier time using the Validator class as Steven suggested, though.

这篇关于如何手动调用ValidationAttributes? (DataAnnotations和ModelState中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆