Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ModelState.IsValid is false - But Which One - Easy Way

In ASP.NET MVC, when we call a post action with some data, we check ModelState and in case some validation error, it would be falst. For a big Enter User Information form, it is annoying to expand each Value and look at the count to see which Key (9 in attached example image) has validation error. Wondering if someone knows an easy way to figure out which element is causing validation error.

enter image description here

like image 742
SBirthare Avatar asked Jun 27 '14 13:06

SBirthare


2 Answers

In VS2015+, you can use LINQ in the Immediate Window, which means you can just run the following:

ModelState.SelectMany(
    x => x.Value.Errors, 
    (state, error) => $"{state.Key}:  {error.ErrorMessage}"
)
like image 167
Arithmomaniac Avatar answered Oct 22 '22 23:10

Arithmomaniac


I propose to write a method:

namespace System.Web
{
    using Mvc;

    public static class ModelStateExtensions
    {
        public static Tuple<string, string> GetFirstError(this ModelStateDictionary modelState)
        {
            if (modelState.IsValid)
            {
                return null;
            }

            foreach (var key in modelState.Keys)
            {
                if (modelState[key].Errors.Count != 0)
                {
                    return new Tuple<string, string>(key, modelState[key].Errors[0].ErrorMessage);
                }
            }

            return null;
        }
    }
}

Then during debugging open Immediate Window and enter:

ModelState.GetFirstError()
like image 34
cryss Avatar answered Oct 22 '22 22:10

cryss