Search code examples
asp.net-mvcenumsasp.net-corehtml.dropdownlistforeditorformodel

How to display Enum as DropDownList in .Net MVC Core


I have a class called Options where I'm keeping a bunch of enumerables for different options. One of these is a Sizes enumerable which is used in my Ball model. How do I get my Size field for my Ball to display as a dropdown list when creating a new Ball? I assume I need to make an Editor Template but I don't know what that's supposed to look like.

Here's some example code:

Options.cs

public class Options
{
    public enum Sizes
    {
        Small,
        Medium,
        Large
    };

    public enum Material
    {
        Rubber,
        Plastic,
        Metal
    };
}

Ball.cs

public class Ball
{
    public string Name { get; set; }
    public Options.Sizes Size { get; set; }
    public Options.Material Material { get; set; }
}

Index.cshtml @model WebApplication.Models.Ball

<form asp-action="Create" asp-controller="Ball">
    @Html.EditorForModel()
    <input type="submit" value="Submit"/>
</form>

How do I get EditorForModel to display the enum properties as DropDownLists with the possible values of the Enum?


Solution

  • I figured it out with a bit of help from this source

    I didn't create a helper like it suggests but I used the same principles from the helper to create a EditorTemplate for my Sizes enum. Here's what it looks like:

    Sizes.cshtml

    @model Options.Sizes 
    
    @{ 
        var values = Enum.GetValues(typeof(Options.Sizes)).Cast<Options.Sizes>();
    
        IEnumerable<SelectListItem> items =
            from value in values
            select new SelectListItem
            {
                Text = value.ToString(),
                Value = value.ToString(),
                Selected = (value.Equals(Options.Sizes.ATX_Full))
            };
    }
    
    @Html.DropDownList("Size", items)
    

    Now when I call @Html.EditorForModel() in my Ball.cshtml, it references this editor template and creates a dropdown with all the options in the enum.