简体   繁体   English

在asp.net mvc3中获取下拉列表的枚举

[英]Get Enums for dropdownlist in asp.net mvc3

This is my enum 这是我的枚举

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

Now i want to add this as a dropdownlist in my controller 现在我想将此添加为控制器中的下拉列表

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

and In my view binded it as.. 在我看来,将其绑定为

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

but, it is showing error 但是,它显示错误

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

Could anyone help me 谁能帮我

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

use: 采用:

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

I use this method: 我使用这种方法:

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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM