Using enum for dropdown list in asp net mvc core

Using enum for list in ASP.NET MVC Core

Dropdown lists are a common UI element used in web applications to allow users to select an option from a list. In ASP.NET MVC Core, we can use enums to populate dropdown lists with predefined options. This provides a more structured and type-safe way of dropdown lists compared to using hard-coded values or database queries.

To demonstrate how to use enums for dropdown lists in ASP.NET MVC Core, let's consider a scenario where we have a “Product” model with a “Category” property. We want to a dropdown list of categories when creating or a product.

First, let's define an enum for the categories:


public enum Category
{
    Electronics,
    Clothing,
    Books,
    HomeAppliances
}

Next, in our “Product” model, we can add a property of type “Category” to represent the selected category:


public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Category Category { get; set; }
}

Now, let's create a view model for the product form, which includes a property to hold the selected category value:


public class ProductViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Category SelectedCategory { get; set; }
    public IEnumerable Categories { get; set; }
}

In the controller action responsible for rendering the product form, we can populate the “Categories” property of the view model with the available categories:


public IActionResult Create()
{
    var  = new ProductViewModel
    {
        Categories = Enum.GetValues(typeof(Category))
                        .Cast()
                        .Select(c => new SelectListItem
                        {
                            Value = c.ToString(),
                            Text = c.ToString()
                        })
    };

    return View(viewModel);
}

Now, in the view, we can use the “Html.” helper to generate the dropdown list:


@model ProductViewModel

@Html.DropDownListFor(model => model.SelectedCategory, Model.Categories, "Select a category", new { @class = "form-control" })

The “Html.DropDownListFor” method takes the property for the selected category, the list of categories, a option text, and HTML attributes for the dropdown list.

When the form is submitted, the selected category value will be bound to the “SelectedCategory” property of the view model in the controller action.

Conclusion

Using enums for dropdown lists in ASP.NET MVC Core provides a more structured and type-safe approach compared to hard-coding values or querying a database. By defining an enum for the dropdown options and binding it to the view model, we can easily populate and handle dropdown lists in our web applications.

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents