How to get the values of an enum into a SelectList

前端 未结 12 945
醉梦人生
醉梦人生 2020-12-13 11:58

Imagine I have an enumeration such as this (just as an example):

public enum Direction{
    Horizontal = 0,
    Vertical = 1,
    Diagonal = 2
}
相关标签:
12条回答
  • 2020-12-13 12:23
    return
                Enum
                .GetNames(typeof(ReceptionNumberType))
                .Where(i => (ReceptionNumberType)(Enum.Parse(typeof(ReceptionNumberType), i.ToString())) < ReceptionNumberType.MCI)
                .Select(i => new
                {
                    description = i,
                    value = (Enum.Parse(typeof(ReceptionNumberType), i.ToString()))
                });
    
    0 讨论(0)
  • 2020-12-13 12:23

    maybe not an exact answer to the question, but in CRUD scenarios i usually implements something like this:

    private void PopulateViewdata4Selectlists(ImportJob job)
    {
       ViewData["Fetcher"] = from ImportFetcher d in Enum.GetValues(typeof(ImportFetcher))
                                  select new SelectListItem
                                  {
                                      Value = ((int)d).ToString(),
                                      Text = d.ToString(),
                                      Selected = job.Fetcher == d
                                  };
    }
    

    PopulateViewdata4Selectlists is called before View("Create") and View("Edit"), then and in the View:

    <%= Html.DropDownList("Fetcher") %>
    

    and that's all..

    0 讨论(0)
  • 2020-12-13 12:28

    I have more classes and methods for various reasons:

    Enum to collection of items

    public static class EnumHelper
    {
        public static List<ItemDto> EnumToCollection<T>()
        {
            return (Enum.GetValues(typeof(T)).Cast<int>().Select(
                e => new ItemViewModel
                         {
                             IntKey = e,
                             Value = Enum.GetName(typeof(T), e)
                         })).ToList();
        }
    }
    

    Creating selectlist in Controller

    int selectedValue = 1; // resolved from anywhere
    ViewBag.Currency = new SelectList(EnumHelper.EnumToCollection<Currency>(), "Key", "Value", selectedValue);
    

    MyView.cshtml

    @Html.DropDownListFor(x => x.Currency, null, htmlAttributes: new { @class = "form-control" })
    
    0 讨论(0)
  • This is what I have just made and personally I think its sexy:

     public static IEnumerable<SelectListItem> GetEnumSelectList<T>()
            {
                return (Enum.GetValues(typeof(T)).Cast<T>().Select(
                    enu => new SelectListItem() { Text = enu.ToString(), Value = enu.ToString() })).ToList();
            }
    

    I am going to do some translation stuff eventually so the Value = enu.ToString() will do a call out to something somewhere.

    0 讨论(0)
  • 2020-12-13 12:32

    I wanted to do something very similar to Dann's solution, but I needed the Value to be an int and the text to be the string representation of the Enum. This is what I came up with:

    public static IEnumerable<SelectListItem> GetEnumSelectList<T>()
        {
            return (Enum.GetValues(typeof(T)).Cast<int>().Select(e => new SelectListItem() { Text = Enum.GetName(typeof(T), e), Value = e.ToString() })).ToList();
        }
    
    0 讨论(0)
  • 2020-12-13 12:32
        public static SelectList ToSelectList<TEnum>(this TEnum enumObj) where TEnum : struct
        {
            if (!typeof(TEnum).IsEnum) throw new ArgumentException("An Enumeration type is required.", "enumObj");
    
            var values = from TEnum e in Enum.GetValues(typeof(TEnum)) select new { ID = (int)Enum.Parse(typeof(TEnum), e.ToString()), Name = e.ToString() };
            //var values = from TEnum e in Enum.GetValues(typeof(TEnum)) select new { ID = e, Name = e.ToString() };
    
            return new SelectList(values, "ID", "Name", enumObj);
        }
        public static SelectList ToSelectList<TEnum>(this TEnum enumObj, string selectedValue) where TEnum : struct
        {
            if (!typeof(TEnum).IsEnum) throw new ArgumentException("An Enumeration type is required.", "enumObj");
    
            var values = from TEnum e in Enum.GetValues(typeof(TEnum)) select new { ID = (int)Enum.Parse(typeof(TEnum), e.ToString()), Name = e.ToString() };
            //var values = from TEnum e in Enum.GetValues(typeof(TEnum)) select new { ID = e, Name = e.ToString() };
            if (string.IsNullOrWhiteSpace(selectedValue))
            {
                return new SelectList(values, "ID", "Name", enumObj);
            }
            else
            {
                return new SelectList(values, "ID", "Name", selectedValue);
            }
        }
    
    0 讨论(0)
提交回复
热议问题