如何手动调用验证归因? (数据通道和模型斯泰特省)
-
09-10-2019 - |
题
在某些逻辑中,我们需要通过模型的属性来迭代自动绑定属性,并希望扩展功能,以在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个属性是从验证归类中得出的,但是当代码通过验证函数(带有空或空值)时,它确实会符合预期。
我希望我正在做一些愚蠢的事情,所以想知道是否有人使用了这种功能并可以提供帮助。
预先感谢杰米
其他提示
您确实使用 System.ComponentModel.DataAnnotations.Validator
验证对象的类。
不隶属于 StackOverflow