One of the most annoying things on ASP.NET MVC is to create a decent dropdown list, and Scott Allen already covered it here nicely. While I like his explanation I often see people facing different scenarios. What I will describe here is the way I use to create the dropdown lists for all my projects.
- Create a common place dropdowns will be placed, so we can maintain it easily;
- Get the data from somewhere;
- Put the minimum necessary logic into the Controller;
- Show it in the View.
First of all, we need a class. I will use a Model, as example, since this data can also come from the database.
This class has only 2 properties since it’s all you need to use with a DropDownListFor. But keep in mind that your class can have other properties.
Now, we need the code to generate the items for the DropDownListFor.
I have this code in a helper specially build for dropdown lists. In this way, as mentioned before, I can ease the maintenance of the project. And if you didn't notice, this code is concatenating with the DefaultItem property, which I show below.
This property will add the standard "-SELECT-" item at the first position in our dropdown list.
Also, you will see once you download the code that I am hard coding the items in the DropDownListHelper's constructor. In the real world I would load the data directly in the property.
Now that we have the class (Model) and the helper, we will go for the ViewModel. This is a pretty standard situation: I personally like to keep my Model exclusively for database while my ViewModel is the one going to create the forms. The reason is that I can customize the ViewModel for my needs, not needing to have a Model with a lot of properties using [NotMapped] on the top.
Here is what we need in the ActionMethod.
And here is the View.
Some might say it’s an unnecessary effort, and I would agree if we would use only one dropdown list. However, when we start building bigger systems which are going to use multiple dropdown lists, this approach comes in handy.
You can check the full code in my GitHub repository: https://github.com/davidsonsousa/DropDownList