How do I populate a dropdownlist with enum values?

前端 未结 5 1042
栀梦
栀梦 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:09

    Maybe is too late, but i think it could be useful for people with the same problem. I've found here that now with MVC 5 it's included an EnumDropDownListFor html helper that makes for no longer necesary the use of custom helpers or other workarounds.

    In this particular case, just add this:

        @Html.EnumDropDownListFor(x => x.SelectedCurrency)
    

    and that's all!

    You can also translate or change the displayed text via data annotations and resources files:

    1. Add the following data annotations to your enum:

      public enum Currencies
      {
          [Display(Name="Currencies_CAD", ResourceType=typeof(Resources.Enums)]  
          CAD, 
          [Display(Name="Currencies_USD", ResourceType=typeof(Resources.Enums)]    
          USD,
          [Display(Name="Currencies_EUR", ResourceType=typeof(Resources.Enums)]  
          EUR
      }
      
    2. Create the corresponding resources file.

提交回复
热议问题