2012-10-22 29 views
0

這是我的枚舉獲取下拉列表枚舉在asp.net MVC3

public class Woodshape 
    { 
     public enum eWoodShape 
     { 
      Round = 10, 
      Oval = 20, 
      Plain = 30 
     } 
    } 

現在我想在我的控制器

public ActionResult Create() 
     { 
      List<string> li = new List<string>(); 
      FieldInfo[] myEnumFields = typeof(Woodshape.eWoodShape).GetFields(); 
      foreach (FieldInfo myField in myEnumFields) 
      { 
       if (!myField.IsSpecialName && myField.Name.ToLower() != "notset") 
       { 
        int myValue = (int)myField.GetValue(0); 
        li.Add(myField.Name); 
       } 
      } 
      ViewBag.ddlEnumshape = new SelectList(myEnumFields, "myValue", "Name"); 

      return View(); 
     } 

,並在我看來綁定它添加爲一個下拉列表。 。

<div> 
@Html.DropDownList("ddlEnumshape", "-Select shape-") 
/<div> 

但是,它顯示錯誤

System.Reflection.RtFieldInfo' does not contain a property with the name 'myValue'. 

誰能幫我

回答

0

我用這個方法:

public static Dictionary<int, string> EnumToDictionary<T>() 
    { 
     return Enum.GetValues(typeof (T)).Cast<T>().ToDictionary(x => Convert.ToInt32(x), x => x.ToString()); 
    } 

ViewBag.ddlEnumshape = new SelectList(EnumToDictionary<Woodshape.eWoodShape>, "Key", "Value"); 
1
public static IEnumerable<SelectListItem> GetListEnumWrap<TEnum>() 
     { 
      var items = new List<SelectListItem>(); 
      if (typeof(TEnum).IsEnum) 
      { 
       foreach (var value in Enum.GetValues(typeof(TEnum)).Cast<int>()) 
       { 
        var name = Enum.GetName(typeof(TEnum), value); 
        name = string.Format("{0}", name); 
        items.Add(new SelectListItem() { Value = value.ToString(), Text = name }); 
       } 
      } 
      return items; 
     } 

使用:

@Html.DropDownListFor(m => m.Type, EnumExtensions.GetListEnumWrap<Types>()) 
+0

感謝您的代碼,它的工作 – user1469330

+0

@ ser1469330,請注意,響應來了 – Mediator