using System; using System.Linq.Expressions; namespace Microsoft.AspNetCore.Mvc.ModelBinding { /// /// Provides extension methods for the ASP.NET Core application. /// public static class ModelStateDictionaryExtensions { /// /// Adds the specified to the /// instance that is associated with the key specified as a . /// /// The type of the model. /// The type of the property. /// The instance. /// The model. Only used to infer the model type. /// The that specifies the property. /// The error message to add. /// No member expression provided. public static void AddModelError(this ModelStateDictionary modelState, TModel model, Expression> keyExpression, string errorMessage) { if (modelState is null) throw new ArgumentNullException(nameof(modelState)); string key = ""; var expr = keyExpression.Body as MemberExpression; while (expr != null) { key = expr.Member.Name + (key != "" ? "." + key : ""); expr = expr.Expression as MemberExpression; } if (key == "") throw new InvalidOperationException("No member expression provided."); modelState.AddModelError(key, errorMessage); } } }