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?
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.
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With