如何在单一操作中正确验证多个模型?

时间:2014-01-10 05:45:52

标签: asp.net-mvc asp.net-mvc-4 validation

我有控制器动作,需要多个模型。

 [HttpPost]
    public ActionResult LoginTest(Respondent respondent, List<db.Educations> educations)
    {
       .......
    }

ModelState.IsValid适用于单个模型,但我如何验证所有这些模型?

1 个答案:

答案 0 :(得分:0)

有方法

TryValidateModel(Object)

有关完整信息,请参阅msdn
因此你可以做类似的事情:

[HttpPost]
public ActionResult LoginTest(Respondent respondent, List<db.Educations> educations)
{
   foreach(var education in educations)
   {
     if (!TryValidateModel(education))
       return new HttpException("some education was not valid...");
   }
   // if you reach this, all educations where valid...
   // thus more code such as saving can go here :) 
}