How do you create a dropdownlist from an enum in ASP.NET MVC?

后端 未结 30 1951
不知归路
不知归路 2020-11-21 16:36

I\'m trying to use the Html.DropDownList extension method but can\'t figure out how to use it with an enumeration.

Let\'s say I have an enumeration like

30条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 17:07

    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.

提交回复
热议问题