Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get display annotation value on mvc3 server side code

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 string foo { get; set; }

    [Display(Name = "Bar")]
    public string bar { get; set; }
}

I want to be able to get the value "Foo" on server side with out posting it back to the page, but like an attribute of the class, or something of the sort. Like a @Html.LabelFor(model => model.Foo) But in c# server code.

Is that possible?

Thank you.

like image 260
AJC Avatar asked Dec 30 '25 11:12

AJC


2 Answers

Something like this?

string displayName = GetDisplayName((Dummy x) => x.foo);

// ...

public static string GetDisplayName<T, U>(Expression<Func<T, U>> 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<DisplayAttribute>()
                 .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<T, U>(this T src, Expression<Func<T, U>> 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<DisplayAttribute>()
                 .SingleOrDefault();

    return (attr != null) ? attr.Name : me.Member.Name;
}
like image 140
LukeH Avatar answered Jan 02 '26 01:01

LukeH


You will need to use reflection. Here is a sample console program that does what you want.

class Program
{
    static void Main(string[] args)
    {
        Dummy dummy = new Dummy();
        PropertyInfo[] properties = dummy.GetType().GetProperties();
        foreach (PropertyInfo property in properties)
        {
            IEnumerable<DisplayAttribute> displayAttributes = property.GetCustomAttributes(typeof(DisplayAttribute), false).Cast<DisplayAttribute>();
            foreach (DisplayAttribute displayAttribute in displayAttributes)
            {
                Console.WriteLine("Property {0} has display name {1}", property.Name, displayAttribute.Name);
            }
        }
        Console.ReadLine();
    }
}

public class Dummy
{
    [Display(Name = "Foo")]
    public string foo { get; set; }

    [Display(Name = "Bar")]
    public string bar { get; set; }
}

This would produce the following result:

http://www.codetunnel.com/content/images/reflectresult.jpg

like image 45
Chev Avatar answered Jan 02 '26 00:01

Chev