How to generate dropdown list from enmueration

A lot of time in our applications we have dropdown list that get populated from members of an enumeration. The issue you run into with this is that in your user interface you want to display list entries with text that descriptive or reflect what that member is about. For example if you have a member of an enumeration named "Allowtoexecute". If I want the display test for this enumeration type to be "Allow user to purchase items" then we have to do something different. Yes, you can always implement solution that involves a table in database that has display text. And then you can prepare your dropdown list items that way. But not every single enumeration require to be in database to help user interface.

In this post, I will show how you can use reflection and attributes on enumeration to prepare dropdown list items that show text in list items that are more reflective of what those enumeration members do.

Apply Display attribute to enum members

using System.ComponentModel.DataAnnotations;
public enum TradeType
{
  [Display(Name = "Buy now", Order = 1)]
  BuyNow = 1,
  [Display(Name = "Auction", Order =2)]
  Auction = 2,
  [Display(Name = "Barter item", Order = 3)]
  Barter = 3
}

DisplayAttribute is defined in System.ComponentModel.DataAnnotations assembly. Therefore you will need to add using statement for definition of this attribute.

Use reflection to prepare MVC SelectListItem list

public static class DropdownListExtension
{
 public static List<selectlistitem> GetEnumTypeList(Type enumType, string selectedValue)
 {
     var listItems = new List<selectlistitem>();
     var values = Enum.GetValues(enumType);
     foreach (var value in values)
     {
         var listItem = new SelectListItem()
         {
             Value = value.ToString(),
             Text = value.ToString(),
             Selected = String.CompareOrdinal(value.ToString(), selectedValue) == 0
         };
         var attributes = enumType.GetMember(value.ToString())[0].GetCustomAttributes(typeof(DisplayAttribute),
             false);
         if (!attributes.Any()) continue;
         var display = attributes.First() as DisplayAttribute;
         listItem.Text = display.Name;
         listItems.Add(listItem);
     }
     return listItems;
 }
 public static IList<selectlistitem> InsertSelectItemEntry(this IList<selectlistitem> list, 
        string displayText, string value)
 {
     list.Insert(0, new SelectListItem()
     {
         Text = displayText,
         Value = value,
         Selected = !list.Any(l => l.Selected)
     });
     return list;
 }
}

As you can see from above code, reflection is used to read custom attributes applied to members of enumeration.

Prepare the list from enumeration type

Following code shows example of how this code is used to create list of SelectListItem and then populate view in MVC view.

 public ActionResult Index()
 {
     var model = new TradeViewModel();
     var tradeTypeList = DropdownListExtension.GetEnumTypeList(typeof(TradeType), string.Empty);
     tradeTypeList.InsertSelectItemEntry("Select trade type", "-1");
     ViewBag.TradeTypeList = tradeTypeList;
     return View(model);
 }

@model MvcTest.Models.TradeViewModel
@{
    ViewBag.Title = "Trader";
    var ajaxOptions = new AjaxOptions() {};
}
<div class="panel panel-info">
        <div class="panel-heading">Create new trade</div>
        <div class="panel-body">
        @using (Html.BeginForm("AddTrade", "Home", FormMethod.Post))
        {
            @Html.DropDownListFor(m => m.TradeType, ViewBag.TradeTypeList as List<SelectListItem>, 
            new { @class = "form-control" })
        <br />
        <input type="submit" value="Submit" />
        }
    </div>
</div>

Search

Social

Weather

27.0 °C / 80.5 °F

weather conditions Clear

Monthly Posts

Blog Tags