ModelState.IsValid is false - but which one is an easy way

In ASP.NET MVC, when we call a post-action with some data, we validate the ModelState and in case of some validation error, it would be a hitch. For the large "Enter user information" form, it is annoying to expand each value and look at the counter to see which key (9 in the attached example image) has a verification error. It is surprising if someone knows an easy way to find out which element is causing a validation error.

enter image description here

+4
source share
4 answers

I suggest writing 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, while debugging the open Immediate window, and type:

ModelState.GetFirstError()
+3
source

, OzCode. IDE Visual Studio, , , . , , .

I played with beta testing for several weeks and it turned out to be a very valuable tool. You can request data in the debugger using OzCode. For example, you can query items in ModelStateby filtering using a collection Values.

+2
source

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

ModelState.SelectMany(
    x => x.Value.Errors, 
    (state, error) => $"{state.Key}:  {error.ErrorMessage}"
)
+2
source

Source: https://habr.com/ru/post/1546311/


All Articles