How can I convert an enumeration into a List?

后端 未结 7 1158
难免孤独
难免孤独 2021-01-30 10:31

i have an asp.net-mvc webpage and i want to show a dropdown list that is based off an enum. I want to show the text of each enum item and the id being the int value that the en

7条回答
  •  生来不讨喜
    2021-01-30 10:40

    It's super easy with my extension method. Which also allows you to provide options like adding placeholder, grouping and disabling certain values or groups. Give it a try.

    enum Color
    {       
        Blue,
        [Category("Light")]
        [DisplayName("Light Blue")]
        LBlue,
        [Category("Dark")]
        [DisplayName("Dark Blue")]
        DBlue,
        Red,
        [Category("Dark")]
        [DisplayName("Dark Red")]
        DRed,
        [Category("Light")]
        [DisplayName("Light Red")]
        LRed,
        Green,
        [Category("Dark")]
        [DisplayName("Dark Green")]
        DGreen,
        [Category("Light")]
        [DisplayName("Light Green")]
        LGreen  
    }
    
    var list = typeof(Color).ToSelectList();
    
    //or with custom options
    var list = typeof(Color).ToSelectList(new SelectListOptions { Placeholder = "Please Select A Color"});
    

    Here's the link to the github repo.

提交回复
热议问题