如何找出哪些关键的ModelState有错误 [英] How to figure out which key of ModelState has error

查看:195
本文介绍了如何找出哪些关键的ModelState有错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要如何找出这ModelState中包含一个错误,当ModelState.IsValid是假的钥匙?通常我只会将鼠标悬停在直通名单ModelState.Values​​检查逐项进行错误计数> 0,但现在我的工作具有复杂对象的一些列表视图,共计252项的ModelState(每个对象的每个项目每个列表中有一个ModelState.Keys输入)。

How do I figure out which of the keys in ModelState that contains an error when ModelState.IsValid is false? Usually I would just hover the mouse thru the ModelState.Values list checking item by item for error count > 0. But now I'm working on a view that has some lists of complex objects, totalling 252 ModelState items(each item of each object of each list has an entry on ModelState.Keys).

那么,有没有点出误差源的更简单的方法?

So, is there an easier way to point out the error source?

推荐答案

您可以检查 ViewData.ModelState.Values​​ 收集,看看哪些错误。

You can check the ViewData.ModelState.Values collection and see what are the Errors.

[Httpost]
public ActionResult Create(User model)
{
   if(ModelState.IsValid)
   {
     //Save and redirect
   }
   else
   {
     foreach (var modelStateVal in ViewData.ModelState.Values)
     {
       foreach (var error in modelStateVal.Errors)
       {               
          var errorMessage = error.ErrorMessage;
          var exception = error.Exception;
          // You may log the errors if you want
       }
     }
   }         
   return View(model);
 }
}

这篇关于如何找出哪些关键的ModelState有错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆