Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Key Name from Model State/ Model State Dictionary?

Tags:

c#

asp.net-mvc

I am wondering how do I get the key name from Model Sate or Model State Dictionary.

When you add a error to the dictionary

  modelStateDictionary.AddModelError("key","errorMessage");

you have to specify a key.

I want to get the key name.

 foreach (ModelState modelState in modelStateDictionary.Values) 
            {



            }

I did the above but that only contains the error message I want to know what the key of that was. I only can find to get all keys that gets stored in a list of strings. I want to get it out each time I go through the foreach loop. So can I not get a key name by index or something?

like image 930
chobo2 Avatar asked Dec 09 '25 01:12

chobo2


2 Answers

You can also enumerate the .Keys property

foreach (var key in modelStateDictionary.Keys) 
        {
            ModelState modelState = modelStateDictionary[key];
        }
like image 138
Joel Martinez Avatar answered Dec 10 '25 14:12

Joel Martinez


foreach (KeyValuePair<TKey, TValue> pair in modelStateDictionary)
{
        // You get key and value
           pair.Value;
           pair.Key;
}
like image 32
Kumar Avatar answered Dec 10 '25 15:12

Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!