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.
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 .
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.
AddModelError("Region", "Region is mandatory"); ModelState. IsValid will then return false.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With