ASP.Net MVC 2 Controller的TryValidate不validation模型中的List 项

如何获得模型validation以validation通用列表属性中的子对象。

我有一个模型,我正在尝试validation,这不是发布到服务器的内容,而是发布的一些信息的组合,以及服务器上已有的信息……例如。

... public class A { [Required] public string Property1 { get; set; } } ... public class B { public List Values { get; set; } } ... if (!TryValidateModel(instanceofB)) { //this should fire, as one of A inside B isn't valid. return View(instanceofB); } 

当我尝试validationB的模型实例时,它不会validationValues集合的validation属性。

TryValidateModel方法只下降一个级别,因此它只检查类型B对象上的Validation属性,而不是其嵌套对象。 解决此问题的一种方法是定义您自己的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 properties = item.GetType(). GetProperties().Where(p => p.GetCustomAttributes( typeof(ValidationAttribute), true).Count() > 0); foreach (PropertyInfo property in properties) { // Validate each property. IEnumerable validationAttributes = property.GetCustomAttributes(typeof(ValidationAttribute), true).Cast(); 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; } } 

现在可以使用以下属性validationList

 public class B { [ListValidation] public List 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; } 

我有一个类似的问题,我通过完全避免调用TryValidate来修复。 我调用TryValidate的原因是因为我需要对我的模型进行一些更改然后进行validation。 我最终为模型创建了一个接口,并将默认模型绑定器替换为识别接口并调用我的方法的绑定器。 这一切都发生在框架调用第一次validation之前(这是递归的)。