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.
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}"
)
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With