ModelState.AddModelError not showing any message
Asked Answered
D

3

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?

Dilatometer answered 14/3, 2013 at 8:23 Comment(1)
do you have property with name "PROGRAM_ID" in your model too? and make sure you have the validation helper call as suggested by DarinAlienable
G
12

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

@Html.ValidationMessage("PROGRAM_ID")
Gwyngwyneth answered 14/3, 2013 at 8:25 Comment(2)
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.Gwyngwyneth
no .. I double checked... property name is proper and also its a single value field not an array..Dilatometer
A
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.");
Ailin answered 26/6, 2013 at 0:50 Comment(1)
Follow 2 steps: (As suggested Darin) 1. In controller code add: ModelState.AddModelError("PROGRAM_ID", "Error Msg"); 2. In view: @Html.ValidationMessage("PROGRAM_ID")Prankster
P
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")
Prankster answered 28/1, 2020 at 1:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.