【问题标题】:MVC wire format model binding and validationMVC 有线格式模型绑定和验证
【发布时间】:2013-08-02 01:55:42
【问题描述】:

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

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

【问题讨论】:

    标签: c# asp.net-mvc


    【解决方案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 中的错误。

    【讨论】:

    • 感谢 Matthew 的回答,我会试一试,但关于“KEY”,这是否需要匹配有线格式模型才能突出显示/链接到导致错误的相应字段。即“KEY”=“container.Items[0].Property1”吗?
    • 已将此标记为答案,因为它有助于解决问题。与@Html.ValidationMessage(modelName, message) 关联使用的密钥是modelName = KEY 和message = "*"。
    猜你喜欢
    • 1970-01-01
    • 2013-12-16
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 2013-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多