ASP.NET MVC How to get Model Error details in Controller Action Method When ModelValidation fails
When Working with MVC Model Validations, You may come across a situation where you think you filled all the Required Items in the Form and submitted, but still the ModelState.IsValid
property is returning false. I came across this scenario once when i was inherting a ViewModel from another ViewModel. How do we know what is causing the IsValid property to return false ?
You can check the ViewData.ModelState.Values
collection and see what are the Errors. Here is the sample code
[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); } }