How do I populate a dropdownlist with enum values?

前端 未结 5 1045
栀梦
栀梦 2020-12-03 12:32

I have an enum for one of the properties of my view-model. I want to display a drop-down list that contains all the values of the enum. I can get this to work with the fol

5条回答
  •  借酒劲吻你
    2020-12-03 13:16

    So many good answers - I thought I'sd add my solution - I am building the SelectList in the view (and not in the Controller):

    In my c#:

    namespace ControlChart.Models
    //My Enum
    public enum FilterType { 
    [Display(Name = "Reportable")]    
    Reportable = 0,    
    [Display(Name = "Non-Reportable")]    
    NonReportable,    
    [Display(Name = "All")]    
    All };
    
    //My model:
    public class ChartModel {  
    [DisplayName("Filter")]  
    public FilterType Filter { get; set; }
    }
    

    In my cshtml:

    @using System.ComponentModel.DataAnnotations
    @using ControlChart.Models
    @model ChartMode
    @*..........*@
    @Html.DropDownListFor(x => x.Filter,                           
    from v in (ControlChart.Models.FilterType[])(Enum.GetValues(typeof(ControlChart.Models.FilterType)))
    select new SelectListItem() {
        Text = ((DisplayAttribute)(typeof(FilterType).GetField(v.ToString()).GetCustomAttributes(typeof(DisplayAttribute), false).First())).Name,                             
        Value = v.ToString(),                             
        Selected = v == Model.Filter                           
        })
    

    HTH

提交回复
热议问题