Last active
April 20, 2019 01:23
-
-
Save light-traveller/c97b6bf85f713f13cbbc569d1fbc330f to your computer and use it in GitHub Desktop.
Get ASP.NET ModelState errors (all errors or by a specific field)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.AspNetCore.Http; | |
using Microsoft.AspNetCore.Mvc.ModelBinding; | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
public static class ModelStateExtensions | |
{ | |
/// <summary> | |
/// Extracts error keys and error messages of all model fields | |
/// </summary> | |
/// <param name="modelState">ASP.NET ModelState dictionary</param> | |
/// <returns>A list of key-value pairs</returns> | |
public static List<KeyValuePair<string, string>> GetModelStateErrors(this ModelStateDictionary modelState) | |
{ | |
var errors = new List<KeyValuePair<string, string>>(); | |
foreach (var item in modelState.Where(i => i.Value.Errors.Any())) | |
{ | |
var key = item.Key; | |
var values = item.Value.Errors; | |
foreach (var val in values) | |
{ | |
errors.Add(new KeyValuePair<string, string>(key, val.ErrorMessage)); | |
} | |
} | |
return errors; | |
} | |
/// <summary> | |
/// Extracts error keys and error messages of a particular field in the model | |
/// </summary> | |
/// <param name="modelState">ASP.NET ModelState dictionary</param> | |
/// <param name="fieldName">Name of the model field for which errors should be extracted</param> | |
/// <returns>A list of key-value pairs</returns> | |
public static List<KeyValuePair<string, string>> GetModelStateErrorsForField(this ModelStateDictionary modelState, string fieldName) | |
{ | |
var errors = new List<KeyValuePair<string, string>>(); | |
foreach (var item in modelState.Where(i => i.Key.Equals(fieldName, StringComparison.OrdinalIgnoreCase) && i.Value.Errors.Any())) | |
{ | |
var key = item.Key; | |
var values = item.Value.Errors; | |
foreach (var val in values) | |
{ | |
errors.Add(new KeyValuePair<string, string>(key, val.ErrorMessage)); | |
} | |
} | |
return errors; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment