0

I'm using the following code to export a table to csv using Entity Framework and MVC:

string header = string.Join("\t", properties.Select(p => p.Name).ToArray());

Is there any way to select the display name I set in my model for example displaying "Hours" instead of "hrs":

    [Display(Name = "Hours")]
    public float hrs { get; set; 

Currently I just get all the variable names and not the diaplay names I set. It seems like there should be an easy fix to this, but google isn't being much help.

tereško
  • 58,060
  • 25
  • 98
  • 150
  • Are you attempting to do this via reflection? If so, check out the answer to this question: http://stackoverflow.com/questions/6637679/reflection-get-attribute-name-and-value-on-property – James Wilson Jul 26 '13 at 20:16

1 Answers1

0

If you want to get an attribute from a Property (such as hrs) use the below method

    public static string GetDisplayName(Type type, string prpName)
    {
        PropertyInfo[] props = type.GetProperties();
        foreach (PropertyInfo prop in props)
        {
            if(!prop.Name.Equals(prpName))
            {
                continue;
            }

            object[] attrs = prop.GetCustomAttributes(true);
            foreach (object attr in attrs)
            {
                if (attr is Display)
                {
                    Display dAttr = (Display)attr;
                    return dAttr.Name;
                }
            }
        }

        return null;
    }

If you want to get it for all of them, you should produce a list and work off that.

I would suggest something like this:

    public static string[] GetDisplayNames(Type type)
    {
        PropertyInfo[] props = type.GetProperties();
        string[] dNames = new string[props.Length];
        for (int i = 0; i < dNames.Length; i++)
        {
            PropertyInfo prop = props[i];
            object[] attrs = prop.GetCustomAttributes(true);
            foreach (object attr in attrs)
            {
                if (attr is Display)
                {
                    Display dAttr = (Display)attr;
                    dNames[i] = dAttr.Name;
                    break;
                }
            }

            if (string.IsNullOrEmpty(dNames[i]))
            {
                dNames[i] = prop.Name;
            }
        }

        return dNames;
    }

See:

Community
  • 1
  • 1
jrbeverly
  • 1,611
  • 14
  • 20