Skip to content

Instantly share code, notes, and snippets.

@marciogoularte
Forked from elizabeth-young/ModelExtensions.cs
Created October 28, 2020 17:21
Show Gist options
  • Save marciogoularte/3655da79bd36edf846565956f395d0a9 to your computer and use it in GitHub Desktop.
Save marciogoularte/3655da79bd36edf846565956f395d0a9 to your computer and use it in GitHub Desktop.
Mvc ModelState extensions to get error list from ModelState
using System.Collections.Generic;
using System.Linq;
usingusing System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
namespace Gists.Mvc.Helpers
{
public static class ModelExtensions
{
public static List<string> GetErrorList(this ModelStateDictionary modelState)
{
var errorList = modelState.Values
.SelectMany(x => x.Errors)
.Select(x => x.ErrorMessage).ToList();
return errorList;
}
public static Dictionary<string, List<string>> GetErrors(this ModelStateDictionary modelState)
{
var errorList = modelState
.Where(x => x.Value.Errors.Count > 0)
.ToDictionary(
kvp => kvp.Key,
kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToList()
);
return errorList;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment