Vinoth Kumar
Vinoth Kumar

Reputation: 499

Binding drop down list from Enum in c#

I'm having Enum class and i have to bind the drop down list in asp.net MVC4(using Razor view engine). I can bind the drop down list and can display in view. But i couldn't show the selected item at edit mode. Please any one help me. I'm havin following code

my ViewModelclass

public class UserViewModel
    {
 public string AccountId { get; set; }
        [Required]
        [Display(Name="First Name")]
        public String FirstName { get; set; }
        [Display(Name="Middle Name")]
        public String MiddleName { get; set; }
        [Required]
        [Display(Name="Last Name")]
        public String LastName { get; set; }
        public String UserRoles { get; set; }
} 

and Enum class is,

 public enum UserType // Office User Types
    {
        Officer = 1,
        Administrator = 2,
        Recruiter = 3
    }

and i'm using following code in my controller,

Dictionary<string, string> rolename = Enum.GetValues(typeof(UserType))
   .Cast<UserType>()
   .Select(v => v.ToString())
   .ToDictionary<string, string>(v => v.ToString());
            ViewBag.Roles = rolename;
   return View();

and my view is,

 @Html.DropDownListFor(model => model.UserRoles,new SelectList(ViewBag.Roles, "Key", "Value",Model.UserRoles.ToString()), new { id = "UserRoles" })

Please help me what is my mistake and how to display selected value in dropdown list at edit mode.

Upvotes: 1

Views: 3409

Answers (2)

NinjaNye
NinjaNye

Reputation: 7126

I've created an enum helper that will give you the select list you need from an enum. It will also automatically handle your selected value should you have one. Take a look.

http://jnye.co/Posts/4/creating-a-dropdown-list-from-an-enum-in-mvc-and-c%23

If you implement the following it may fix your issue:

//In the controller
ViewBag.DropDownList = EnumHelper.SelectListFor(myEnumValue);

//In the view
@Html.DropDownList("DropDownList") 

/// OR
@Html.DropDownListFor(m => m.DropDownList, ViewBag.DropDownList as IEnumerable<SelectListItem>)

The above takes advantage of this helper

public static class EnumHelper  
{  
    //Creates a SelectList for a nullable enum value  
    public static SelectList SelectListFor<T>(T? selected)  
        where T : struct  
    {  
        return selected == null ? SelectListFor<T>()  
                                : SelectListFor(selected.Value);  
    }  

    //Creates a SelectList for an enum type  
    public static SelectList SelectListFor<T>() where T : struct  
    {  
        Type t = typeof (T);  
        if (t.IsEnum)  
        {  
            var values = Enum.GetValues(typeof(T)).Cast<enum>()  
                             .Select(e => new { Id = Convert.ToInt32(e), Name = e.GetDescription() });  

            return new SelectList(values, "Id", "Name");  
        }  
        return null;  
    }  

    //Creates a SelectList for an enum value  
    public static SelectList SelectListFor<T>(T selected) where T : struct   
    {  
        Type t = typeof(T);  
        if (t.IsEnum)  
        {  
            var values = Enum.GetValues(t).Cast<Enum>()  
                             .Select(e => new { Id = Convert.ToInt32(e), Name = e.GetDescription() });  

            return new SelectList(values, "Id", "Name", Convert.ToInt32(selected));  
        }  
        return null;  
    }   

    // Get the value of the description attribute if the   
    // enum has one, otherwise use the value.  
    public static string GetDescription<TEnum>(this TEnum value)  
    {  
        FieldInfo fi = value.GetType().GetField(value.ToString());  

        if (fi != null)  
        {  
            DescriptionAttribute[] attributes =  
             (DescriptionAttribute[])fi.GetCustomAttributes(  
    typeof(DescriptionAttribute),  
    false);  

            if (attributes.Length > 0)  
            {  
                 return attributes[0].Description;  
            }  
        }  

        return value.ToString();  
    }  
}  

Upvotes: 0

Jay
Jay

Reputation: 6294

The following code generates a SelectList from and enum

    public static IEnumerable<SelectListItem> EnumToSelectList(System.Type type)
    {
        var output = new List<SelectListItem>();
        foreach (int item in Enum.GetValues(type))
        {
            var si = new System.Web.Mvc.SelectListItem();
            si.Value = item.ToString();

            DisplayAttribute attr =(DataAnnotations.DisplayAttribute)
                type.GetMember(Enum.GetName(type, item))
                .First().GetCustomAttributes(typeof(DataAnnotations.DisplayAttribute), false)
                .FirstOrDefault();
            si.Text = (attr == null) ? Enum.GetName(type, item) : attr.Name;
            output.Add(si);
        }
        return output;

    }

As you can see from the code it also uses Data Annotations DisplayAttribute to help in case the name in the enum name is not "user friendly".

This can also be abstracted as an extension to HtmlHelper though not nessessary.

    public static IEnumerable<SelectListItem> EnumToSelectList(
        this HtmlHelper helper, 
        System.Type type)
    {
        return EnumToSelectList(type);
    }

Usage is simple:

@Html.DropDownListFor(model => model.UserRoles, 
    Html.EnumToSelectList(typeof(UserType))

Upvotes: 1

Related Questions