2015-06-02 39 views
1

我知道如何將枚舉值綁定到DropDownList,但我想使用「漂亮的名字」而不是枚舉值。如何使用「漂亮的名字」在ASP.NET中將枚舉綁定到DropDownList

比如我描述枚舉:

public enum ContainerStatus 
    { 
     [Display(Description = "Container processed")] 
     Processed, 
     [Display(Description = "Container ready to ship")] 
     ReadyToShip, 
     [Display(Description = "Container sent")] 
     Sent 
    } 

我想要的,而不是枚舉值顯示DisplayAttribute值。 你能幫我嗎?

回答

0

您將需要創建一個類來讀取顯示屬性。

完整的源代碼在於:

public enum ContainerStatus 
{ 
    [Display(Description = "Container processed")] 
    Processed, 
    [Display(Description = "Container ready to ship")] 
    ReadyToShip, 
    [Display(Description = "Container sent")] 
    Sent 
} 

public static class EnumExtensions 
{ 
    public static string Description(this Enum value) 
    { 
     var enumType = value.GetType(); 
     var field = enumType.GetField(value.ToString()); 
     var attributes = field.GetCustomAttributes(typeof(DisplayAttribute), 
                false); 
     return attributes.Length == 0 
      ? value.ToString() 
      : ((DisplayAttribute)attributes[0]).Description; 
    } 
} 

public partial class WebForm1 : System.Web.UI.Page 
{ 

    protected void Page_Load(object sender, EventArgs e) 
    {  
     var values = Enum.GetValues(typeof(ContainerStatus)).Cast<ContainerStatus>(); 

     foreach (var v in values) 
     { 
      DropDownList1.Items.Add(v.Description());     
     } 
    } 
} 
1

嘗試通用實現:

public static List<KeyValuePair<string, string>> EnumToList<T>() where T: Enum 
    { 
     var pInfos = typeof(T).GetFields(); 
     List<KeyValuePair<string, string>> displayList = new List<KeyValuePair<string, string>>(); 
     foreach (var pi in pInfos) 
     { 
      if (pi.FieldType == typeof(int)) continue; 
      var attr = pi.GetCustomAttributes(typeof(DisplayAttribute), false); 
      if (attr != null && attr.Length > 0) 
      { 
       var key = pi.Name; 
       var value = (attr[0] as DisplayAttribute).Description; 
       KeyValuePair<string, string> listItem = new KeyValuePair<string, string>(key, value); 
       displayList.Add(listItem); 
      } 
      else 
      { 
       KeyValuePair<string, string> listItem = new KeyValuePair<string, string>(pi.Name, pi.Name); 
       displayList.Add(listItem); 
      } 
     } 
     return displayList; 
    } 

數據綁定方法:

protected void Page_Load(object sender, EventArgs e) 
{ 
    var dataSource = EnumToList<ContainerStatus>(); 
    dropDownList.DataSource = dataSource; 
    dropDownList.DataValueField = "Key"; 
    dropDownList.DataTextField = "Value"; 
    dropDownList.DataBind(); 
} 
相關問題