Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The <code>TryValidateModel</code> method only goes down one level so it only checks for <code>Validation</code> attributes on the object of type <code>B</code>, not on its nested objects. One way to overcome this is to define your own implementation of a <code>ValidationAttribute</code>:</p> <pre><code>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&lt;PropertyInfo&gt; properties = item.GetType(). GetProperties().Where(p =&gt; p.GetCustomAttributes( typeof(ValidationAttribute), true).Count() &gt; 0); foreach (PropertyInfo property in properties) { // Validate each property. IEnumerable&lt;ValidationAttribute&gt; validationAttributes = property.GetCustomAttributes(typeof(ValidationAttribute), true).Cast&lt;ValidationAttribute&gt;(); 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; } } </code></pre> <p>Now <code>List&lt;A&gt;</code> can be validated using the attribute:</p> <pre><code>public class B { [ListValidation] public List&lt;A&gt; Values { get; set; } } </code></pre> <p>I haven't tested performance for the above approach thoroughly but if in your case that turns out to be a problem, an alternative approach is to use a helper function:</p> <pre><code> 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; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload