10

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?

hetal gala
  • 249
  • 2
  • 5
  • 18
  • do you have property with name "PROGRAM_ID" in your model too? and make sure you have the validation helper call as suggested by Darin – K D Mar 14 '13 at 08:33

3 Answers3

12

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

@Html.ValidationMessage("PROGRAM_ID")
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Oh then I guess that you are adding the model error to the wrong key. You probably have an array of those ids. Something like `ModelState.AddModelError("SomeCollection[2].PROGRAM_ID", "Access for this program already exists.");`. Of course all this will depend on your models. – Darin Dimitrov Mar 14 '13 at 10:56
  • no .. I double checked... property name is proper and also its a single value field not an array.. – hetal gala Mar 14 '13 at 12:14
12

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.");
Evonet
  • 3,600
  • 4
  • 37
  • 83
  • Follow 2 steps: (As suggested Darin) 1. In controller code add: ModelState.AddModelError("PROGRAM_ID", "Error Msg"); 2. In view: @Html.ValidationMessage("PROGRAM_ID") – Shakil Jan 28 '20 at 01:07
0

Follow 2 steps: (Darin's solution works)

  1. In controller add: ModelState.AddModelError("PROGRAM_ID", "Error Msg");
  2. In view add: @Html.ValidationMessage("PROGRAM_ID")
camille
  • 16,432
  • 18
  • 38
  • 60
Shakil
  • 51
  • 3