在某些逻辑中,我们需要通过模型的属性来迭代自动绑定属性,并希望扩展功能,以在C#4.0中包含新的DataNannotations。

目前,我基本上在所有验证归因实例中都迭代每个属性加载,并尝试使用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个属性是从验证归类中得出的,但是当代码通过验证函数(带有空或空值)时,它确实会符合预期。

我希望我正在做一些愚蠢的事情,所以想知道是否有人使用了这种功能并可以提供帮助。

预先感谢杰米

有帮助吗?

解决方案

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

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

您肯定会有更轻松的时间 使用验证器类 作为 史蒂文建议, , 尽管。

其他提示

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top