-
-
Save gilday/2407523 to your computer and use it in GitHub Desktop.
This file contains 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
/// <summary> | |
/// Adds a model error using strongly typed lambda expressions | |
/// </summary> | |
public static void AddModelError<TModel>( | |
this ModelStateDictionary modelState, | |
Expression<Func<TModel, object>> method, | |
string message) | |
{ | |
if (method == null) | |
{ | |
throw new ArgumentNullException("method"); | |
} | |
MemberExpression mce = method.Body as MemberExpression; | |
// Handle the case where the property is being converted to typeof(object) | |
if (mce == null && method.Body.NodeType == ExpressionType.Convert) | |
{ | |
UnaryExpression ue = (UnaryExpression)method.Body; | |
mce = (MemberExpression)ue.Operand; | |
} | |
string property = mce.Member.Name; | |
modelState.AddModelError(property, message); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment