David
David

Reputation: 8650

ASP.Net MVC 3 DataAnnotations validating List<T>

I have a ViewModel that has been deserialized from JSON which looks something like this:

public class UserThingsUpdateViewModel
{
    public IList<Thing> Things { get; set; }
    [Required]
    public int UserId { get; set; }
    public int Age { get; set; }
}

Thing is also a ViewModel which also has various DataAnnotaion ValidationAttribute attributes on the properties.

The problem is that Lists don't seem to get validated and even after a through search I cant seem to find any articles that tackle this. Most suggest that the ViewModel is wrong if it includes a list.

So, what is the best way to validate my list and add Model Errors to the Model State?

Upvotes: 1

Views: 1134

Answers (2)

counsellorben
counsellorben

Reputation: 10924

Prior to checking ModelState.IsValid, you could add code to step through and validate each Thing, as follows:

foreach (var thing in Things)
    TryValidateModel(thing);

This will validate each item, and add any errors to ModelState.

Upvotes: 2

Chris Pont
Chris Pont

Reputation: 791

You could write a custom validator attribute and decorate the list property with it? That would allow you to write custom logic to get the elements out of the list and validate them.

Upvotes: 0

Related Questions