Tra*_*er1 3 c# asp.net-mvc-2-validation asp.net-mvc-2
如何获得模型验证以验证通用列表属性中的子对象.
我有一个模型,我正在尝试验证,这不是发布到服务器的内容,而是发布的一些信息的组合,以及服务器上已有的信息......例如.
...
public class A {
[Required]
public string Property1 { get; set; }
}
...
public class B {
public List<A> Values { get; set; }
}
...
if (!TryValidateModel(instanceofB))
{
//this should fire, as one of A inside B isn't valid.
return View(instanceofB);
}
Run Code Online (Sandbox Code Playgroud)
当我尝试验证B的模型实例时,它不会验证Values集合的验证属性.
该TryValidateModel方法仅下降一级,因此它仅检查Validation类型对象上的属性B,而不是其嵌套对象上的属性.克服这个问题的一种方法是定义自己的实现ValidationAttribute:
public class ListValidationAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
IEnumerable enumerable = value as IEnumerable;
// If the input object is not enumerable it's considered valid.
if (enumerable == null)
{
return true;
}
foreach (object item in enumerable)
{
// Get all properties on the current item with at least one
// ValidationAttribute defined.
IEnumerable<PropertyInfo> properties = item.GetType().
GetProperties().Where(p => p.GetCustomAttributes(
typeof(ValidationAttribute), true).Count() > 0);
foreach (PropertyInfo property in properties)
{
// Validate each property.
IEnumerable<ValidationAttribute> validationAttributes =
property.GetCustomAttributes(typeof(ValidationAttribute),
true).Cast<ValidationAttribute>();
foreach (ValidationAttribute validationAttribute in
validationAttributes)
{
object propertyValue = property.GetValue(item, null);
if (!validationAttribute.IsValid(propertyValue))
{
// Return false if one value is found to be invalid.
return false;
}
}
}
}
// If everything is valid, return true.
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
现在List<A>可以使用以下属性进行验证:
public class B
{
[ListValidation]
public List<A> Values { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我没有彻底测试上述方法的性能,但如果在你的情况下结果是一个问题,另一种方法是使用辅助函数:
if (!ValidateB(instanceofB))
{
//this should fire, as one of A inside B isn't valid.
return View(instanceofB);
}
...
public bool ValidateB(B b)
{
foreach (A item in b.Values)
{
if (!TryValidateModel(item))
{
return false;
}
}
return true;
}
Run Code Online (Sandbox Code Playgroud)