I want to reduce typo issues so I need method like ModelStateFor which should accept Expression. nameof()
method is not sufficient because it doesn't work correctly for nested properties.
Asked
Active
Viewed 57 times
1 Answers
0
I created extension for ModelState to handle that case. It also handle case when you use nested property like Input.Login.
public static ModelStateDictionary AddModelErrorFor<TProperty>( this ModelStateDictionary modelState, Expression<Func<TProperty>> expression, string errorMessage )
{
modelState.AddModelError( expression.GetPathOfProperty(), errorMessage );
return modelState;
}
public static string GetPathOfProperty<T>( this Expression<Func<T>> expression )
{
var stringBuilder = new StringBuilder();
var memberExpression = expression.Body as MemberExpression;
while ( memberExpression != null )
{
if ( stringBuilder.Length > 0 )
stringBuilder.Insert( 0, "." );
stringBuilder.Insert( 0, memberExpression.Member.Name );
memberExpression = memberExpression.Expression as MemberExpression;
}
return stringBuilder.ToString();
}
PathOfProperty method is based on this question

Daniel
- 68
- 5