【问题标题】:How to call ValidationAttributes manually? (DataAnnotations and ModelState)如何手动调用验证属性? (DataAnnotations 和 ModelState)
【发布时间】:2011-05-24 12:49:23
【问题描述】:

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

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

提前致谢, 杰米

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 您有使用 ASP.Net MVC 3.0 的 DataAnnotations 4.0 的示例吗,我目前使用的是 3.5(可能有效,也可能无效,我正在将代码从 MVC 1.0 升级到 3)
    • 如果我没记错的话,MVC 2 及更高版本默认使用 DataAnnotations,因此在使用 MVC 3 时,您不必手动调用验证器。
    • 基本上我们希望将流程卸载到一个单独的机制中,因此希望能够自动绑定并手动运行验证。
    【解决方案2】:

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

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

    不过,using the Validator class 和 Steven suggested 一样,你肯定会更轻松。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-06
      相关资源
      最近更新 更多