我们需要在某些逻辑中迭代模型的属性以自动绑定(bind)属性,并希望扩展功能以包含 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 值)时,它确实按预期抛出了异常。
我期待我在做一些愚蠢的事情,所以想知道是否有人使用过这个功能并且可以提供帮助。
提前致谢,
杰米
最佳答案
这是因为您将源对象传递给 Validate
方法,而不是属性值。以下更可能按预期工作(尽管显然不适用于索引属性):
attrib.Validate(propertyInfo.GetValue(obj, null), propertyInfo.Name);
你肯定会更轻松using the Validator class作为 Steven suggested , 尽管。
关于asp.net - 如何手动调用验证属性? (DataAnnotations 和 ModelState),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4426854/