Web窗体 - 转发器的枚举显示值

时间:2016-11-06 16:03:50

标签: asp.net enums webforms

我有一个对象列表,我想使用以下代码绑定到转发器(不一定以表格格式显示):

C#目标代码:

public enum CategoryEnum
{
    [Description("Entertainment and Film")]
    EntertainmentFilm = 1,
    [Description("Audio and Music Cover")]
    AudioCover = 2,
    [Description("Others")]
    Others = 0
}

public class Document
{
    public string Name { get; set; }
    public CategoryEnum Category { get; set; }
}

Web窗体代码:

        <asp:Repeater id="listDoc" runat="server" >
            <ItemTemplate>
                <tr>
                    <td><asp:Label id="lblName" runat="server" Text='<%#Eval("Name") %>'/></td>
                    <td><asp:Label id="lblCategory" runat="server" Text='<%#Eval("Category") %>'/></td>
                </tr>
            </ItemTemplate>
        </asp:Repeater>

有没有办法将结果显示为

  

名称 |的类别
  music1 |音频和音乐封面
  movie1 |娱乐和电影
  movie2 |娱乐和电影
  series1 |娱乐和电影
  运动|其他

而不是:

  

名称 |的类别
  music1 | AudioCover
  movie1 | EntertainmentFilm
  movie2 | EntertainmentFilm
  series1 | EntertainmentFilm
  运动|其他

或者有更好的方法吗?

提前致谢!

2 个答案:

答案 0 :(得分:0)

public static class EnumHelper<T>
   {
       public static string GetEnumDescription(string value)
       {
           Type type = typeof(T);
           var name = Enum.GetNames(type).Where(f => f.Equals(value, StringComparison.CurrentCultureIgnoreCase)).Select(d => d).FirstOrDefault();

           if (name == null)
           {
               return string.Empty;
           }
           var field = type.GetField(name);
           var customAttribute = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
           return customAttribute.Length > 0 ? ((DescriptionAttribute)customAttribute[0]).Description : name;
       }
   }

var movieDesc = EnumHelper<CategoryEnum>.GetEnumDescription("EntertainmentFilm");
var audioDesc = EnumHelper<CategoryEnum>.GetEnumDescription("AudioCover");
var othersDesc = EnumHelper<CategoryEnum>.GetEnumDescription("Others");

上面是一个示例,说明如何从Enum值中获取描述。希望它有所帮助

答案 1 :(得分:0)

您可以在&#34;文档&#34;中添加这2个成员。类。一个是获取类别值的只读属性,并将第二个成员调用为使用反射来获取枚举描述的静态函数:

public string CategoryDescription
    {
        get
        {
            return GetEnumDescription(this.Category);                                
        }
    }

public static string GetEnumDescription(Enum value)
    {
        FieldInfo fi = value.GetType().GetField(value.ToString());

        DescriptionAttribute[] attributes =
            (DescriptionAttribute[])fi.GetCustomAttributes(
            typeof(DescriptionAttribute),
            false);

        if (attributes != null &&
            attributes.Length > 0)
            return attributes[0].Description;
        else
            return value.ToString();
    }