41 lines
1.7 KiB
C#
41 lines
1.7 KiB
C#
using System;
|
|
using System.Linq.Expressions;
|
|
|
|
namespace Microsoft.AspNetCore.Mvc.ModelBinding
|
|
{
|
|
/// <summary>
|
|
/// Provides extension methods for the ASP.NET Core application.
|
|
/// </summary>
|
|
public static class ModelStateDictionaryExtensions
|
|
{
|
|
/// <summary>
|
|
/// Adds the specified <paramref name="errorMessage"/> to the <see cref="ModelStateEntry.Errors"/>
|
|
/// instance that is associated with the key specified as a <see cref="MemberExpression"/>.
|
|
/// </summary>
|
|
/// <typeparam name="TModel">The type of the model.</typeparam>
|
|
/// <typeparam name="TProperty">The type of the property.</typeparam>
|
|
/// <param name="modelState">The <see cref="ModelStateDictionary"/> instance.</param>
|
|
/// <param name="model">The model. Only used to infer the model type.</param>
|
|
/// <param name="keyExpression">The <see cref="MemberExpression"/> that specifies the property.</param>
|
|
/// <param name="errorMessage">The error message to add.</param>
|
|
/// <exception cref="InvalidOperationException">No member expression provided.</exception>
|
|
public static void AddModelError<TModel, TProperty>(this ModelStateDictionary modelState, TModel model, Expression<Func<TModel, TProperty>> 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);
|
|
}
|
|
}
|
|
}
|