New to Telerik UI for ASP.NET Core? Download free 30-day trial

Populating a Form DropDownList with Enum Values

Environment

Product Version 2023.1.314
Product DropDownList for ASP.NET Core

Description

I want to populate a Telerik UI for ASP.NET Core DropDownList editor of a Form with the Enum values and bind them to the model. How can I do this?

Solution

To achieve the desired results:

  1. Use the Html.GetEnumSelectList() to get the SelectList of the available options.

  2. Use the BindTo() configuration of the DropDownList to bind to the returned SelectList.

Refer to this REPL example for a runnable demo of the snippet below:

@using System.ComponentModel 
@functions{
    public enum Difficulty { Easy, Normal, Hard }

    public class MyModel
    {
        public string Name {get;set;}
        public Difficulty SelectedOption {get; set;}
    }
}

@{
    var modelData = new MyModel(){Name = "Player 1", SelectedOption = Difficulty.Normal};
}

@(Html.Kendo().Form<MyModel>()
        .Name("exampleForm")
        .FormData(modelData)
        .HtmlAttributes(new { action = "Items", method = "POST" })
        .Validatable(v =>
        {
            v.ValidateOnBlur(true);
            v.ValidationSummary(vs => vs.Enable(true));
        })
        .Items(items =>
        {
            items.AddGroup()
                .Label("Choose Game settings")
                .Items(i =>
                {
                    i.Add()
                         .Field(f => f.Name)
                         .Label(l => l.Text("Player Name:"));

                    i.Add()
                        .Field(f => f.SelectedOption)
                        .Label(l => l.Text("Difficulty:"))
                        .Editor(e =>
                        {
                            e.DropDownList()
                                .DataTextField("Text")
                                .DataValueField("Value")
                                .Height(520)
                                .BindTo(Html.GetEnumSelectList<Difficulty>());  
                        });
                });
        })
    )

More ASP.NET Core DropDownList Resources

See Also

In this article