ModelState.AddModelError not showing any message

19,717

Solution 1

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.");

Solution 2

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

@Html.ValidationMessage("PROGRAM_ID")
Share:
19,717
hetal gala
Author by

hetal gala

Updated on July 10, 2022

Comments

  • hetal gala
    hetal gala almost 2 years

    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?

    • K D
      K D about 11 years
      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
  • Darin Dimitrov
    Darin Dimitrov about 11 years
    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.
  • hetal gala
    hetal gala about 11 years
    no .. I double checked... property name is proper and also its a single value field not an array..
  • Shakil
    Shakil over 4 years
    Follow 2 steps: (As suggested Darin) 1. In controller code add: ModelState.AddModelError("PROGRAM_ID", "Error Msg"); 2. In view: @Html.ValidationMessage("PROGRAM_ID")