2015-07-20 37 views
4

我有一個枚舉與顯示說明屬性,MVC EnumDropDownListFor與枚舉顯示說明屬性作爲值

public enum CSSColours 
    { 
     [Display(Description = "bg-green")] 
     Green, 

     [Display(Description = "bg-blue")] 
     Blue, 
    } 

現在我想此枚舉綁定到一個DropDownList,示出了在枚舉值(綠,藍)下拉菜單項顯示文本和描述作爲項值(bg-green,bg-blue)。

當我結合具有EnumDropDownListFor輔助方法

@Html.EnumDropDownListFor(c => dm.BgColor) 

它的項目值設置爲枚舉值(0,1),並且不能找到一種方法,將值設置爲顯示說明下拉。

如何將值設置爲Enum顯示描述屬性?

+0

它的討論http://stackoverflow.com/questions/13099834/how-to-get-the-display-name-attribute-of-an-enum-member-via -mvc-razor-code – cutit

回答

6

你需要得到顯示名(DisplayAttribute)從枚舉, 檢查實施例下面以設置枚舉顯示說明屬性

動作(結合下拉列表)

public ActionResult Index() 
     { 
      var enumDataColours = from CSSColours e in Enum.GetValues(typeof(CSSColours)) 
          select new 
          { 
           ID = StaticHelper.GetDescriptionOfEnum((CSSColours)e), 
           Name = e.ToString() 
          }; 
      ViewBag.EnumColoursList = new SelectList(enumDataColours, "ID", "Name"); 
      return View(); 
     } 

Helper方法GetDescriptionOfEnum的值,以得到描述屬性按枚舉名稱

public static class StaticHelper 
    { 
     public static string GetDescriptionOfEnum(Enum value) 
     { 
      var type = value.GetType(); 
      if (!type.IsEnum) throw new ArgumentException(String.Format("Type '{0}' is not Enum", type)); 

      var members = type.GetMember(value.ToString()); 
      if (members.Length == 0) throw new ArgumentException(String.Format("Member '{0}' not found in type '{1}'", value, type.Name)); 

      var member = members[0]; 
      var attributes = member.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.DisplayAttribute), false); 
      if (attributes.Length == 0) throw new ArgumentException(String.Format("'{0}.{1}' doesn't have DisplayAttribute", type.Name, value)); 

      var attribute = (System.ComponentModel.DataAnnotations.DisplayAttribute)attributes[0]; 
      return attribute.Description; 
     } 
    } 

剃刀視圖

@Html.DropDownList("EnumDropDownColours", ViewBag.EnumColoursList as SelectList) 

枚舉

public enum CSSColours 
    { 
     [Display(Description = "bg-green")] 
     Green, 

     [Display(Description = "bg-blue")] 
     Blue, 
    } 
+0

我在這個答案中唯一改變的是將DropDownList更改爲DropDownListFor,如下所示: '@ Html.DropDownListFor(m => m.CSSColour,ViewBag.CSSColours as SelectList,「Select一」)' – Gwasshoppa