How do I populate a dropdownlist with enum values?

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

    I am very late on this one but I just found a really cool way to do this with one line of code, if you are happy to add the Unconstrained Melody NuGet package (a nice, small library from Jon Skeet).

    This solution is better because:

    1. It ensures (with generic type constraints) that the value really is an enum value (due to Unconstrained Melody)
    2. It avoids unnecessary boxing (due to Unconstrained Melody)
    3. It caches all the descriptions to avoid using reflection on every call (due to Unconstrained Melody)
    4. It is less code than the other solutions!

    So, here are the steps to get this working:

    1. In Package Manager Console, "Install-Package UnconstrainedMelody"
    2. Add a property on your model like so:

      //Replace "YourEnum" with the type of your enum
      public IEnumerable AllItems
      {
          get
          {
              return Enums.GetValues().Select(enumValue => new SelectListItem { Value = enumValue.ToString(), Text = enumValue.GetDescription() });
          }
      }
      

    Now that you have the List of SelectListItem exposed on your model, you can use the @Html.DropDownList or @Html.DropDownListFor using this property as the source.

提交回复
热议问题