How do you get a model's validation to also validate child objects in a generic list property.
I have a model that I'm trying to validate, this is not what's being posted to the server, but a composite of some information posted, and information already on the server... for example.
...
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);
}
When I try to validate the model instance of B, it won't validate the Values collection for their validation attributes.
I had a similar issue that I fixed by avoiding the call to TryValidate altogether. The reason I called TryValidate was because I needed to do make some changes on my model and then do the validation. I ended up creating an interface for the model and replaced the default model binder with one that recognizes the interface and calls my method. This all happens before the framework calls validate the first time (which is recursive).
The
TryValidateModel
method only goes down one level so it only checks forValidation
attributes on the object of typeB
, not on its nested objects. One way to overcome this is to define your own implementation of aValidationAttribute
:Now
List<A>
can be validated using the attribute: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: