locked
Make dropdownlist in ASP.NET MVC using an enum RRS feed

  • Question

  • User38624581 posted

    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 this:

    public enum ItemTypes
    {
        Movie = 1,
        Game = 2,
        Book = 3
    }

    How do I go about creating a dropdown with these values using the Html.DropDownList extension method?

    Or is my best bet to simply create a for loop and create the Html elements manually?

    Wednesday, June 6, 2018 6:16 PM

All replies

  • User-369506445 posted

    hi

    if you use an enum , it's better use Html.EnumDropDownList instead of Html.DropDownList.

     public enum ItemTypes
        {
            Movie = 1,
            Game = 2,
            Book = 3
        }

    ViewModel

    public class YourViewModel
        {
            //Other properties
            [Range(1, int.MaxValue, ErrorMessage = "Select a Items")]
            public ItemTypes ItemTypes { get; set; }
        }


    and View

    @model WebApplication.Controllers.YourViewModel
     
    @Html.EnumDropDownListFor(m => m.ItemTypes, "Select a Item", new { @class = "form-control" })



    Thursday, June 7, 2018 5:14 AM
  • User1724605321 posted

    Hi Sachinsboa,

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

    Please refer to this reply : https://stackoverflow.com/a/694361/5751404 

    For MVC v5.1 use Html.EnumDropDownListFor :

    @Html.EnumDropDownListFor(
        x => x.YourEnumField,
        "Select My Type", 
        new { @class = "form-control" })

    For MVC v5 use EnumHelper

    @Html.DropDownList("MyType", 
       EnumHelper.GetSelectList(typeof(MyType)) , 
       "Select My Type", 
       new { @class = "form-control" })

    For MVC 5 and lower :

    namespace MyApp.Common
    {
        public static class MyExtensions{
            public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
                where TEnum : struct, IComparable, IFormattable, IConvertible
            {
                var values = from TEnum e in Enum.GetValues(typeof(TEnum))
                    select new { Id = e, Name = e.ToString() };
                return new SelectList(values, "Id", "Name", enumObj);
            }
        }
    }

    Best Regards,

    Nan Yu

    Thursday, June 7, 2018 6:12 AM
  • User-131059102 posted

    This works for me and is super simple:

    <select asp-for="Fish.FishCatagories" class="form-control" asp-items="@Html.GetEnumSelectList<FishCatagories>()"></select>

    Saturday, June 9, 2018 9:56 AM
  • User16909594 posted

    Waw thanks!!! This is super simple indeed. Why is this the first thing I found about it online :(

    Wednesday, May 8, 2019 4:15 PM