I am working on an MVC2 application and want to set the maxlength attributes of the text inputs.
I have already defined the stringlength attribute on the Model objec
Here are some static methods you can use to get the StringLength, or any other attribute.
using System;
using System.Linq;
using System.Reflection;
using System.ComponentModel.DataAnnotations;
using System.Linq.Expressions;
public static class AttributeHelpers {
public static Int32 GetStringLength(Expression> propertyExpression) {
return GetPropertyAttributeValue(propertyExpression,attr => attr.Length);
}
//Optional Extension method
public static Int32 GetStringLength(this T instance,Expression> propertyExpression) {
return GetStringLength(propertyExpression);
}
//Required generic method to get any property attribute from any class
public static TValue GetPropertyAttributeValue(Expression> propertyExpression,Func valueSelector) where TAttribute : Attribute {
var expression = (MemberExpression)propertyExpression.Body;
var propertyInfo = (PropertyInfo)expression.Member;
var attr = propertyInfo.GetCustomAttributes(typeof(TAttribute),true).FirstOrDefault() as TAttribute;
if (attr==null) {
throw new MissingMemberException(typeof(T).Name+"."+propertyInfo.Name,typeof(TAttribute).Name);
}
return valueSelector(attr);
}
}
Using the static method...
var length = AttributeHelpers.GetStringLength(x => x.Address1);
Or using the optional extension method on an instance...
var player = new User();
var length = player.GetStringLength(x => x.Address1);
Or using the full static method for any other attribute...
var length = AttributeHelpers.GetPropertyAttributeValue(prop => prop.Address1,attr => attr.MaximumLength);
Inspired by the answer here... https://stackoverflow.com/a/32501356/324479