Skip to content

Instantly share code, notes, and snippets.

@gilday
Forked from kouphax/gist:632863
Created April 17, 2012 17:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gilday/2407523 to your computer and use it in GitHub Desktop.
Save gilday/2407523 to your computer and use it in GitHub Desktop.
/// <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