Jam*_*mie 6 asp.net modelstate validationattribute data-annotations asp.net-mvc-3
我们需要在一些逻辑中迭代模型的属性以自动绑定属性,并希望扩展功能以在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;
}
}
Run Code Online (Sandbox Code Playgroud)
检查属性的代码是:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我调试了代码,模型确实有3个属性,其中2个是从ValidationAttribute派生的,但是当代码通过Validate函数(带有空值或空值)时,它会按预期抛出异常.
我期待我做一些愚蠢的事情,所以我想知道是否有人使用过这个功能并且可以提供帮助.
先谢谢,杰米
这是因为您将源对象传递给Validate方法,而不是属性值。以下更有可能按预期工作(尽管显然不适用于索引属性):
attrib.Validate(propertyInfo.GetValue(obj, null), propertyInfo.Name);
Run Code Online (Sandbox Code Playgroud)
不过,正如Steven 建议的那样,使用 Validator 类肯定会更轻松。
| 归档时间: |
|
| 查看次数: |
4692 次 |
| 最近记录: |