【问题标题】:string.join/properties.select by display name instead of variable namestring.join/properties.select 按显示名称而不是变量名称
【发布时间】:2013-07-27 05:53:38
【问题描述】:

我正在使用以下代码使用 Entity Framework 和 MVC 将表导出到 csv:

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

有什么方法可以选择我在模型中设置的显示名称,例如显示“小时”而不是“小时”:

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

目前我只获取所有变量名称,而不是我设置的显示名称。似乎应该有一个简单的解决方案,但谷歌并没有太大帮助。

【问题讨论】:

标签: asp.net-mvc string entity-framework


【解决方案1】:

如果你想从一个Property中获取一个属性(比如hrs),使用下面的方法

    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;
    }

如果您想为所有这些人获取它,您应该制作一个列表并完成它。

我会建议这样的事情:

    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;
    }

见:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    相关资源
    最近更新 更多