MVC有线格式模型绑定和验证

时间:2013-06-19 18:20:06

标签: c# asp.net-mvc

使用有线格式模型绑定时,如何处理模型验证?我希望在验证摘要区域中有验证消息,并突出显示未能验证的受影响的输入字段。

//Model
public class Container 
{
   List<Item> Items { get; set;}
}

//View
@Html.ValidationSummary()

@foreach (var item in Model.Items) { 
   <div>
   @<text><input type="hidden" name="container.Items[@item.Index].Property1" value = "@item.Property1" /></text>
   @<text><input type="text" name="container.Items[@item.Index].Property2" value = "@item.Property2" /></text>
   </div>
}

//Controller Action
[HttpPost]
public ActionResult DoSomething(Container container){
   //Call DB - retrieve DB messages - but then how do you add validation summary messages from DB exceptions.

   return view(container);
}

1 个答案:

答案 0 :(得分:1)

您可以在控制器中使用ModelState.AddModelError,如下所示:

[HttpPost]
public ActionResult DoSomething(Container container){
   var error = Model.GetErrors();  //Change this to whatever call you need to validate the Container
   if(error.HasErrors)
   {
       ModelState.AddModelError("KEY",error.Message);
   }

   return view(container);
}

这将添加将在ValidationSummary中显示的错误。

相关问题