Josh Russo
Josh Russo

Reputation: 3241

How to get model validation to pickup attributes set on objects in a List in MVC3?

I have a set of models that looks similar to this

public class OtherModel 
{
    [Required]
    string name { get; set; }
}

public class OthersEditModel 
{
    List<OtherModel> others { get; set; }
}

I then have a controller method that looks like this

[HttpPost]
public ActionResult EditOthers(OthersEditModel others)
{
    if(ModelState.IsValid)
    {
         // Save
    }
}

My problem is that the ModelState.IsValid isn't triggering the validation of the objects in the list.

How do I accomplish this, or is it even possible?

Or alternatively can I manually trigger the validation of the elements in the list?

Upvotes: 3

Views: 344

Answers (2)

Josh Russo
Josh Russo

Reputation: 3241

So it turns out that the problem wasn't the validation properties. They pick up perfectly, without doing anything to the base OthersEditModel. I had broken the dynamic JavaScript form generation, so the form fields were coming back with incorrect names.

By the way, this http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx is an excellent extension to MVC 3

Upvotes: 1

Kristoffer Schroeder
Kristoffer Schroeder

Reputation: 688

[HttpPost]
public ActionResult EditOthers(OthersEditModel others)
{
    if(ModelState.IsValid)
    {
         foreach (var item in others.others)
        {
            if(!TryValidateModel(item))
                //Not valid
        }
    }
}

Upvotes: 0

Related Questions