user1469330
user1469330

Reputation: 45

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

Upvotes: 0

Views: 662

Answers (2)

Mediator
Mediator

Reputation: 15378

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

Upvotes: 1

karaxuna
karaxuna

Reputation: 26930

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

Upvotes: 0

Related Questions