I am using telerik mvc grid. In my table I have unique key defined for a field. And in controller I am catching the error using try ... catch inside DbUpdateException.
in catch block I want to handle the error and show error messsage in view. So using following line,
ModelState.AddModelError("PROGRAM_ID", "Access for this program already exists.");
return View();
But this is not showing error message. Any idea why?
To clear the memory of the model state you need to use ModelState. Clear(). You could also remove only the desired field by using method of ModelState.
IsValid is false now. That's because an error exists; ModelState. IsValid is false if any of the properties submitted have any error messages attached to them. What all of this means is that by setting up the validation in this manner, we allow MVC to just work the way it was designed.
AddModelError(String, String) Adds the specified error message to the errors collection for the model-state dictionary that is associated with the specified key.
Make sure that you have a corresponding ValidationMessage
in your view with the same key:
@Html.ValidationMessage("PROGRAM_ID")
ValidationSummary will only display ModelErrors for string.empty as the key. To display an error added with ModelState.AddModelError in your validationsummary, change your code to:
ModelState.AddModelError(string.Empty, "Access for this program already exists.");
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