Creating A Drop Down List From An Enum In ASP.NET MVC

0 views
Skip to first unread message
Message has been deleted

Gaia Shaw

unread,
Jul 16, 2024, 11:47:07 AM7/16/24
to cevinnakann

Every Enum type derives from System.Enum. There are two static methods that help bind data to a drop-down list control (and retrieve the value). These are Enum.GetNames and Enum.Parse. Using GetNames, you are able to bind to your drop-down list control as follows:

Creating a drop down list from an enum in ASP.NET MVC


Download Zip https://tinurll.com/2yVOKj



After reading all posts I came up with a comprehensive solution to support showing enum description in dropdown list as well as selecting proper value from Model in dropdown when displaying in Edit mode:

Why not use like this to be able pass every listControle :public static void BindToEnum(Type enumType, ListControl lc) // get the names from the enumeration string[] names = Enum.GetNames(enumType); // get the values from the enumeration Array values = Enum.GetValues(enumType); // turn it into a hash table Hashtable ht = new Hashtable(); for (int i = 0; i < names.Length; i++) // note the cast to integer here is important // otherwise we'll just get the enum string back again ht.Add(names[i], (int)values.GetValue(i)); // return the dictionary to be bound to lc.DataSource = ht; lc.DataTextField = "Key"; lc.DataValueField = "Value"; lc.DataBind(); And use is just as simple as :BindToEnum(typeof(NewsType), DropDownList1);BindToEnum(typeof(NewsType), CheckBoxList1);BindToEnum(typeof(NewsType), RadoBuuttonList1);

I know I'm late to the party on this, but thought you might find this variant useful, as this one also allows you to use descriptive strings rather than enumeration constants in the drop down. To do this, decorate each enumeration entry with a [System.ComponentModel.Description] attribute.

[Update - just noticed this, and the code looks like an extended version of the code here: -net-mvc-creating-a-dropdownlist-helper-for-enums/, with a couple of additions. If so, attribution would seem fair ;-)]

Introduction

Sometimes, we have a scenario during development where we need to populate DropDownList from Enum. There are a couple of ways to do it. But every way has its pros and cons. One should always keep in mind the SOLID and DRY principle while writing code. I will show two ways to do it and you will be able to understand which one is better and why it is better.

Approach 1 (Typical Way)

The first approach in my point of view is not very elegant, but it will surely do what we want it to.

Consider the following Enum which we want to populate in the drop down:

I have a grid with inline editing. I have set an editor template for a column to have a dropdown list. This column is bound to a property that is set according to an enum. All of that works great, and I get a dropdown with the names.

I populate the DropDownList using a SelectListItem type list. So we need to first create a list from an enum and thereafter that list binds with the DropDownListFor method of the HTML Helper class on the view. Create a model (ActionModel class) under the Models folder.

ASP.NET Core has built-in Html.GetEnumSelectList() method we can use to turn enum members to select list items. The method is intelligent enough to support Display attribute and therefore we can use custom names for enum members and even translations from resource files. Well, until we have full control over enum. If enum comes from external library then we will get the names it has and if we want to change something then we have to find some other solution.

In the above example, the first parameter in DropDownListFor() method is a lambda expression that specifies the model property to be bind with the select element. We have specified the StudentGender property. The second parameter specifies the items to show into a dropdown list using SelectList object. The third parameter is optional, which will be the first item of dropdownlist. So now, it generates control with two list items - Male & Female, as shown below.

In the above example, the first parameter is a property name for which we want to display list items. The second parameter is a list of values to be included in the dropdown list. We have used Enum methods to get the Gender values. The third parameter is a label, which will be the first list item, and the fourth parameter is for HTML attributes like CSS to be applied on the dropdownlist.

Seemingly simple things, such as creating a humble drop down list with elements from a given enumcan be quite perplexing, and lots of people get stuck there, not even knowing how to start. In thisarticle I will show in just a few simple steps how to do the following:

Check out my previous article Using simple Drop Down Lists in ASP.NET MVC for the detailedbreakdown on how to create a simple drop down list on a form, populate it with values from acontroller, send selected value back and render the drop down with the value selected.

The problem comes with front end interaction. I have many places where I want enums to be selectable via drop down lists and the like. This works okay on the surface, but I ran across an issue with the actual relationship between enums and JSON as a language/format. These issues were not overcome by using the traditional [JsonConverter(typeof(StringEnumConverter))] attribute in my models.

Now what this meant is that even if I used fancy footwork to convert my enums into strings for my dropdownlists, they still get saved back to the database as integers; Or rather it is more sufficient to say that they get saved in Raven as strings, but still 'considered' as integers upon deserialization back to the javascript components/MVC.

So with this, I can plug this into anything that expects JSON data, for example in my situation, I am using Kendo UI and their DropDownList component with RemoteDataSource, it is easy to make drop down lists bound to simple objects.

Mostly we bind dropdown list with a list coming from database but let suppose I have a list of four-five records and I want to show these items in dropdown list. In this case I don't want to first save these in database and then retrieve from database as list and binding to my dropdown list. What if I can create a simple Enum for my list and can bind my dropdown list with this. Here in this article I will try to explain, how can we bind a dropdown list from a enum in MVC.

Now I am creating a controller and naming it as ExampleController and will put some code in it to create a list from enum and put in ViewData. Below is my controller code. My function GetEnumList() is simply creating a SelectList from enum and adding DataValue and DataText to it.

As developers we often need some sort of decision from editors where they should be able to choose from a limited number of options. There are ways of accomplishing that out-of-the-box by using drop down list properties or categories. None of them are very developer friendly though.

Prior to ASP.NET MVC 5, the only way to bind an enum to a drop down list in an MVC view was to roll out your own HtmlHelper, which is the best way to extend MVC's functionality. These days, with MVC 5 at your disposal, you can bind any enum to a view control easily by calling the "oh so handy" EnumDropDownListFor HTML helper. Details on the helper can be found here and works like any other build in HTML helper, with a model, a model property and a bunch of additional attributes that allow you to decorate your drop down list.

First, let's see what the problem is with the current (i.e. EnumDropDownListFor) implementation in MVC 5. Using the helper, the values in the drop down box, which is bound to the enum in your model, will look like this:

To improve the appearence of the values in the bound drop down, we can decorate the enum values with the Description attribute. The description can contain the readable text that you want to display to your users without compromising the ease that comes from binding directly to an enum. Enough with the talking - show me the code!

Normally, in an ASP.NET application we'd render an enumeration as a Drop Down List. Problem is we don't want to show "BurntOrange" as a value in the drop down list, we want to show a nice friendly option like "Burnt Orange".

The web development world is considering ASP.NET MVC seriously. Unlike ASP.NET Web Form controls, the Html Helpers are not rich for MVC but growing. Recently, I needed a DropDownListFor HTML Helper where we could simply pass the LINQ Expression for the model property (where the property is an enum type) and we wanted to let the helper create the HTML Select element with all enum values. When creating the select list, we wanted to show a meaningful string for Display Type, where a string could contain space, special character etc. Obviously, an enum value cannot contain space and special character etc. So, wanted to decorate some of the enum members with Description Attribute so that, the Select list can display those Description attribute as display field where the original enum member name would be used as Value field. Finally, we came up with a DropDownListFor overload HTML helper. I thought this tiny utility is worth sharing. So, here is what I came up with.

Allot of people get confused and assume that because they need a drop down list for a typed view, that it must be IEnumerable or IList or whatever sort of collection in the model, this is not true for single select items from lists.

If your enum starts at 0, this will result in an extra option with an empty value appearing in the list. However, the first enum (in my example, Coal) will still be selected by default. If you start your enum from 1, the "Pick One" option will be generated with a value of 0, which will be selected by default and will also form a valid selection if you make the property required via the DataAnnotation [Required] attribute. So what if you don't want the "Pick One" option being assigned a value and/or don't want the option with a value of 0 to be selected by default? You can solve both these problems by making the enum nullable in your view model:

aa06259810
Reply all
Reply to author
Forward
0 new messages