该TryValidateModel
方法只下降了一层,因此它只检查Validation
type 对象的属性B
,而不是其嵌套对象。克服这个问题的一种方法是定义您自己的 a 实现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;
}
}
现在List<A>
可以使用属性进行验证:
public class B
{
[ListValidation]
public List<A> Values { get; set; }
}
我没有彻底测试上述方法的性能,但如果在你的情况下结果是一个问题,另一种方法是使用辅助函数:
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;
}