How to get model validation to pickup attributes s

2019-07-03 22:50发布

问题:

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?

回答1:

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



回答2:

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