Is there a way to get the value of an annotation in server side code? For example, I have:
public class Dummy
{
[Display(Name = \"Foo\")]
public stri
Something like this?
string displayName = GetDisplayName((Dummy x) => x.foo);
// ...
public static string GetDisplayName(Expression> exp)
{
var me = exp.Body as MemberExpression;
if (me == null)
throw new ArgumentException("Must be a MemberExpression.", "exp");
var attr = me.Member
.GetCustomAttributes(typeof(DisplayAttribute), false)
.Cast()
.SingleOrDefault();
return (attr != null) ? attr.Name : me.Member.Name;
}
Or, if you want to be able to call the method against an instance and take advantage of type inference:
var dummy = new Dummy();
string displayName = dummy.GetDisplayName(x => x.foo);
// ...
public static string GetDisplayName(this T src, Expression> exp)
{
var me = exp.Body as MemberExpression;
if (me == null)
throw new ArgumentException("Must be a MemberExpression.", "exp");
var attr = me.Member
.GetCustomAttributes(typeof(DisplayAttribute), false)
.Cast()
.SingleOrDefault();
return (attr != null) ? attr.Name : me.Member.Name;
}