C# MVC wire格式模型绑定和验证

C# MVC wire格式模型绑定和验证,c#,asp.net-mvc,C#,Asp.net Mvc,使用wire格式模型绑定时如何处理模型验证。我希望在验证摘要区域中显示验证消息,并突出显示未验证的受影响输入字段 //Model public class Container { List<Item> Items { get; set;} } //View @Html.ValidationSummary() @foreach (var item in Model.Items) { <div> @<text><input type

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

//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);
}
//模型
公营货柜
{
列表项{get;set;}
}
//看法
@Html.ValidationSummary()
@foreach(Model.Items中的var项){
@
@
}
//控制器动作
[HttpPost]
公共行动结果剂量测定法(容器){
//调用DB-检索DB消息-然后如何从DB异常添加验证摘要消息。
返回视图(容器);
}
您可以在控制器中使用,如下所示:

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

感谢Matthew的回答,我将尝试一下,但关于“键”,这是否需要匹配wire格式模型,以突出显示/链接到导致错误的相应字段。i、 e.“KEY”=“container.Items[0].Property1”是否已将其标记为答案,因为它有助于解决问题。该键与@Html.ValidationMessage(modelName,message)关联使用,分别为modelName=key和message=“*”。