How to figure out which key of ModelState has error

后端 未结 2 1194
遥遥无期
遥遥无期 2020-11-28 14:28

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

相关标签:
2条回答
  • 2020-11-28 14:55

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

    If you really want the Keys(the property name), You can iterate through the ModelState.Keys

    foreach (var modelStateKey in ViewData.ModelState.Keys)
    {
        var modelStateVal = ViewData.ModelState[modelStateKey];
        foreach (var error in modelStateVal.Errors)
        {
            var key = modelStateKey; 
            var errorMessage = error.ErrorMessage;
            var exception = error.Exception;
            // You may log the errors if you want
        }
    }
    
    0 讨论(0)
  • 2020-11-28 14:59
    ModelState.Values.SelectMany(v => v.Errors);
    

    is considered cleaner.

    0 讨论(0)
提交回复
热议问题