Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value from ModelState with key name

Tags:

c#

asp.net-mvc

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?

like image 330
None Avatar asked Jan 25 '17 06:01

None


People also ask

How do you get a ModelState value?

var value = ViewData. ModelState[modelStateKey]; foreach (var error in value. Errors) { //present it //... } } j.v.

What does ModelState AddModelError do?

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.

Why ModelState IsValid is false in MVC?

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.


1 Answers

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
        //...
    }
}
like image 154
j.v. Avatar answered Oct 20 '22 03:10

j.v.