Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ModelState.AddModelError - How can I add an error that isn't for a property?

I am checking my database in Create(FooViewModel fvm){...} to see if the fvm.prop1 and fvm.prop2 already exist in that combination; if so, I want to add an error to the modelstate, then return the whole view. I tried:

public ActionResult Create(FooViewModel fvm){     if (ThatComboAlreadyExists(fvm)) {       ModelState.AddModelError("Model", "There is already one like that");       return View(fvm);     } } 

...but I get no display of errors in the Html.ValidationSummary, which is where I assume they would appear. I have the suspicion that "Model" is not the right key, but I haven't been able to find anything a la Google.

like image 828
Scott Baker Avatar asked Apr 21 '11 04:04

Scott Baker


People also ask

How do you add errors in ModelState?

Above, we added a custom error message using the ModelState. AddModelError() method. The ValidationSummary() method will automatically display all the error messages added into the ModelState .

Which property is used to determine an error in ModelState?

Errors property and the ModelState. IsValid property. They're used for the second function of ModelState : to store the errors found in the submitted values.

How do you make a ModelState IsValid false?

AddModelError("Region", "Region is mandatory"); ModelState. IsValid will then return false.

How do I display ModelState errors?

The ModelState object is a dictionary and it has a keys property that will contain the name of the property in the model causing the error. The keys property is a collection of all the keys in the dictionary. You can get the name of the first key by doing something like this: var firstPropertyName = ModelState.


1 Answers

I eventually stumbled upon an example of the usage I was looking for - to assign an error to the Model in general, rather than one of it's properties, as usual you call:

ModelState.AddModelError(string key, string errorMessage); 

but use an empty string for the key:

ModelState.AddModelError(string.Empty, "There is something wrong with Foo."); 

The error message will present itself in the <%: Html.ValidationSummary() %> as you'd expect.

like image 54
Scott Baker Avatar answered Sep 20 '22 13:09

Scott Baker