Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get error message if ModelState.IsValid fails?

I have this function in my controller.

[HttpPost] public ActionResult Edit(EmployeesViewModel viewModel) {     Employee employee = GetEmployee(viewModel.EmployeeId);     TryUpdateModel(employee);      if (ModelState.IsValid)     {         SaveEmployee(employee);         TempData["message"] = "Employee has been saved.";         return RedirectToAction("Details", new { id = employee.EmployeeID });     }      return View(viewModel); // validation error, so redisplay same view } 

It keeps failing, ModelState.IsValid keeps returning false and redisplaying the view. But I have no idea what the error is.

Is there a way to get the error and redisplay it to the user?

like image 964
Steven Avatar asked Mar 06 '11 17:03

Steven


People also ask

How do I get ModelState error message in controller?

You can use SelectMany function c# to get error message from modelstate mvc. It will generate error message string it contains modelstate errors; we can return as json and display in html element. You have to define validations inside the class as per requirement.

How do I get ModelState error in view?

Above, we added a custom error message using the ModelState. AddModelError() method. The ValidationSummary() method will automatically display all the error messages added into the ModelState .

How do I know if my ModelState IsValid?

Just place them just in front / at the place where you check ModelState. isValid and hover over the ModelState. Now you can easily browse through all the values inside and see what error causes the isvalid return false.


1 Answers

Try this

if (ModelState.IsValid) {     //go on as normal } else {     var errors = ModelState.Select(x => x.Value.Errors)                            .Where(y=>y.Count>0)                            .ToList(); } 

errors will be a list of all the errors.

If you want to display the errors to the user, all you have to do is return the model to the view and if you haven't removed the Razor @Html.ValidationFor() expressions, it will show up.

if (ModelState.IsValid) {     //go on as normal } else {     return View(model); } 

The view will show any validation errors next to each field and/or in the ValidationSummary if it's present.

like image 153
Captain Kenpachi Avatar answered Sep 28 '22 23:09

Captain Kenpachi