如何手动调用ValidationAttributes? (数据注释和模型状态)
我们的某些逻辑中需要迭代模型的属性以自动绑定属性,并希望扩展功能以包含 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 值)它确实按预期抛出了异常。
我预计我会做一些愚蠢的事情,所以我想知道是否有人使用过此功能并且可以提供帮助。
提前致谢, 杰米
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.
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;
}
}
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);
}
}
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为您将源对象传递给
Validate
方法,而不是属性值。以下内容更有可能按预期工作(尽管显然不适用于索引属性):您肯定会更轻松 按照 Steven 建议使用 Validator 类 ,不过。
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):You would certainly have an easier time using the Validator class as Steven suggested, though.
您可以使用 System.ComponentModel.DataAnnotations.Validator 类来验证对象。
You do use the
System.ComponentModel.DataAnnotations.Validator
class to validate objects.