0

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

//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);
}
4

1 回答 1

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 中的错误。

于 2013-06-19T18:25:26.047 回答