I am adding some error messages to my ModelState
from controller so that I can display it in my view. My Code is like this
ModelState.AddModelError(key: "MyError", errorMessage: "This phone number is already in use. Please register with a different phone number.");
And in my view I am displaying it like this
foreach (ModelState modelState in ViewData.ModelState.Values)
{
var errors = modelState.Errors;
if (errors.Any())
{
foreach (ModelError error in errors)
{
<p class="common-error">@error.ErrorMessage</p>
}
}
}
One issue with this approach is that, It is displaying all kind of ModelState
errors where I want only to show error messages with a key MyError
. how can I make this?
var value = ViewData. ModelState[modelStateKey]; foreach (var error in value. Errors) { //present it //... } } j.v.
ModelState treats your errors exactly the way it treats errors generated by model binding: When you add an error using AddModelError, the ModelState's IsValid property is automatically set to false. So, after all your additional validation errors, you can just check IsValid to see if you've turned up any new errors.
That's because an error exists; ModelState. IsValid is false if any of the properties submitted have any error messages attached to them. What all of this means is that by setting up the validation in this manner, we allow MVC to just work the way it was designed.
You can iterate through keys like this:
foreach (var modelStateKey in ViewData.ModelState.Keys)
{
//decide if you want to show it or not...
//...
var value = ViewData.ModelState[modelStateKey];
foreach (var error in value.Errors)
{
//present it
//...
}
}
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