Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ModelState.AddModelError not showing any message

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?

like image 772
hetal gala Avatar asked Mar 14 '13 08:03

hetal gala


People also ask

How do I reset my ModelState?

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.

Why is my ModelState IsValid false?

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.

What is ModelState AddModelError?

AddModelError(String, String) Adds the specified error message to the errors collection for the model-state dictionary that is associated with the specified key.


2 Answers

Make sure that you have a corresponding ValidationMessage in your view with the same key:

@Html.ValidationMessage("PROGRAM_ID")
like image 59
Darin Dimitrov Avatar answered Oct 08 '22 06:10

Darin Dimitrov


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.");
like image 43
Evonet Avatar answered Oct 08 '22 05:10

Evonet