Convert your ModelState into a string array

May 17th, 2016 Duco Winterwerp asp.net .net mvc

With this little piece of code, you can turn your ModelState into a simple string array. I always use this piece of code, because I make use of flash messages (my own custom validation messages).

public static string[] ToStringArray(this ModelStateDictionary modelState)
{
    return modelState
        .Values
        .Where(v => v.Errors.Count > 0)
        .SelectMany(ms => ms.Errors)
        .Select(e => e.ErrorMessage)
        .ToArray();
}

When you want to use this piece of code, all you need to do is something like this:

if(!ModelState.IsValid)
{
    var messages = ModelState.ToStringArray();
    ...
}
...