Buda Gavril
Buda Gavril

Reputation: 21627

web api: get invalid fields from the model

Is there a way to relate the error from the Modelstate.Values with the invalid fields from the model?

I have something like

foreach (var error in this.ModelState.Values)
{
    Console.WriteLine(error.Errors);
}

But this code returns only errors.

Upvotes: 1

Views: 2850

Answers (3)

kyleruss
kyleruss

Reputation: 497

You can get both the error messages and their associated parameters from the ModelState and store them in a key-value pairs by:

var Errors = ModelState.Keys.Where(i => ModelState[i].Errors.Count > 0)
.Select(k => new KeyValuePair<string, string>(k, ModelState[k].Errors.First().ErrorMessage));

This Linq query first checks and selects only the parameters that have errors and from those parameters we want to select both the parameter name and its associated error message which we store in key-value pairs.

Upvotes: 3

Jinish
Jinish

Reputation: 2073

ModelState is just a Dictionary with Key and Value pairs. So it you wanted to get the property and its associated errors you would do:

foreach (var modelError in ModelState)
{
    string propertyName = modelError.Key;
    if (modelError.Value.Errors.Count > 0)
    {
        //...
    }
}

Upvotes: 2

Jinish
Jinish

Reputation: 2073

You should try:

error.Errors.SelectMany(x => x.ErrorMessage)

in case you need to get the error messages out. (You would need reference to System.Linq)

Upvotes: 0

Related Questions