top of page
Search
faron1991

Creating a drop down list from an enum in ASP.NET MVC with custom HTML helpers and lambda expression



We need to provide a template for MVC to handle Enums in order for it to render them as a dropdown list. We could provide a template whose name matches our Enum (AirlinePreference) and in that view render our dropdown. We could also supply a UIHint attribute on our model property, to help MVC find our template. I prefer to alter the string template, to look for a property type of Enum and render all Enums in my models by the same piece of code without having to be explicit about it with each Enum in each model. This helps have a consistent way of rendering an Enum the same way on all pages with the least amount of code.


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:




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



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.


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:


This article completes my look at dropdownlists in ASP.NET MVC. It looks at how to manage multiple selections and explores the new helper introduced in MVC 5.1 to support the use of enumerations in dropdownlists. If you would like to review the more common uses of the DropDownList helpers, please take some time to read the first article.


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!


If the user knows your enum values they can type in a value and model binding works correctly, but we certainly don't want users to guess the valid values. A better approach would use a drop down list, or a set of radio buttons, to constrain and guide the user's input. There are a few articles on the web showing how to build a drop down list from enums (Stuart Leeks has a good one - Creating a DropDownList helper for enums). I wanted to try a slightly different approach using templates and supporting localization. If you are familiar with templates in ASP.NET MVC, see Brad Wilson's series on templates and metadata).


The implementation of the template is straightforward. Regardless of the type of UI you want, you'll need to use Enum.GetValues to get all the possible values of the enumeration. You can then use the values to build a drop down list, radio buttons, anything you can image. The following code would render a simple drop down list.


DropDownList is a visual control with down arrow which displays a list of items and forces you to choose only one item at a time. DropDownList is not editable, it means the user cannot enter own value and limited to choose an item from the selection.


Recently I got a question from one of the readers that how to work with Enums in ASP.NET MVC? Before we move ahead in this post, let me tell you that it is very simple to work with Enums in ASP.NET MVC 5.1 and later. In MVC 5.1, HTML helper class EnumDropDownListFor has been introduced which is used to display the Enum in a dropdown as shown in the image below:


In this blog post, we have seen different ways to bind Enum data to dropdown list. The easiest way is to use the inbuilt GetEnumSelectList HtmlHelper method. Hope, It helps. Enjoy ASP.NET Core MVC !!


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.


In MVC we have EnumDropDownListFor which we can directly bind with our any enum, it is very similar to DropDownListFor. In this article we will try to create an enum and use it into our model and see how we can bind and save it into the database. As we know we cannot keep space in the name of emum members so how we can use a clear text into dropdown than the enum members. It is easy we will use Data Annotation Attribute to achieve the clear text to show. If you will search on net, there are many people will suggest you to create your own helper but it is available in our MVC project and we don't need to write a single line of code, we can directly use it like other TextBoxFor, DropDownListFor...


In the above example , i have an enum BlockbusterMovies which needs to be bound to the dropdownlist. Enum.GetValues is used to get the values from the Enum which is used in the LINQ Query to form the List and then assigned to the ViewData which is bound to the dropdownlist.


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.


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.


Not a particularly mind-blowing post today, but I found this little bit of code helpful and it might help someone else. So here you go. A simple html helper for ASP.NET MVC for creating drop downs based on Enumeration values. The nice bit is that it will respect Data Annotations Describe attributes.


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.


To create a custom editor template, create a folder named EditorTemplates under Views->Shared folder. So that the editor templates gets available to all the Views.Now create a Partial View under that folder with name as your Enum (which is here ExpertiseArea so partial view file name will be ExpertiseArea.cshtml). Now in this View we need to create the drop down list. For dropdown list, we need to get all the item names from the Enum Type and create the items for drop down. So here my my partial view ExpertiseArea.cshtml contains


In above code, We are getting all the names and values from Enum and creating the items for dropdown and once we create the items, we used the dropdown list helper to populate the dropdown. So now lets render the create the page again.


Now a dropdown is rendered with all the possible enum type values for enum type property. And the same will be used at many places, wherever we want to get the user input on this enum value. And there will be no change in the Views.


The implementation of EnumDropDownListFor is based on a few articles I found on the Internet, where the following one looked like the most complete and stable implementation: -helper-for-enums/. For more background, and a way to localize these drop-downs, check out these resources:


In my implementation I added the SplitString method (and renamed it to PascalCaseToSpaces) as suggested by Nick in the blog post from Stuart Leeks to change PascalCasedEnumItems to a version with spaces (Pascal Cased Enum Items) in the drop-down list.


In this article you saw how to use the model and repositories developed in earlier parts in the series for an ASP.NET MVC 4 application. In particular, you saw how to use a dependency framework to inject concrete instances of the IPeopleRepository and IUnitOfWork interfaces into the controllers of the project. A good part of the article was then spent discussing the implementation of the PeopleRepository and its methods to implement CRUD (Create, Read, Update and Delete) operations. At the end of the article, you saw how validation is handled and how enums are used to create better looking drop-down lists via extension methods. 2ff7e9595c


0 views0 comments

Recent Posts

See All

Going balls hack apk baixar

MadOut2 Big City Online APK + OBB Download: um guia para usuários do Android Você ama jogos no estilo GTA com mundo aberto, carros, armas...

Comments


bottom of page