Create Modern ASP.NET MVC Dropdown Lists - 3 Steps

Create Modern ASP.NET MVC Dropdown Lists - 3 Steps

The complete guide to creating modern UI drop down lists in ASP.NET MVC in very simple steps using Razor and Bootstrap for professional results

Create Modern ASP.NET MVC Dropdown Lists - 3 Steps

The following topics will be discussed in this post.

The first step in creating an MVC dropdown list is to create the data source from which the drop-down list will read its data. 

To perform this step, you only need to call your business logic method which returns a list of specific enumerable items and pass the resulting enumerable list to the MVC ViewBag. 

Your business logic could be calling an MSSQL database, files or just return some static elements in an enumerable list.

For more information about the MVC ViewBag please check the MSDN: ControllerBase.ViewBag Property

In this blog post, I will use a method that will return a list of type ApplicationTypeModel. The ApplicationTypeModel class should look like the following code snippet:

Where Id is the unique identifier of the ApplicationTypeModel and ApplicationName is the name that will be later used in the drop-down configurations. The following snippet shows the full line of code that populates the ViewBag with the list of ApplicationTypeModel.

ViewBag.ApplicationTypes = _SectionAPI.GetAllApplicationTypes();


The above snippet should be placed in the MVC action that renders the View, which you will put your dropdown list markup in it.

Step 1 Achievement: By finishing step 1, you should have created a server-side data source which will be used to populate the drop-down list in the further steps using MVC Razor.

Step 2: The DropDown list Razor Markup

This step is as simple as connecting/populating the ViewBag.ApplicationTypes created in step 1 to the drop-down list and configuring the other settings to build the desired drop down UI and behavior. The Razor syntax that builds the dropdown list will be like the following code snippet:

@Html.DropDownList("ApplicationType", new SelectList(ViewBag.ApplicationTypes, "Id", "ApplicationName"), " - Select Type - ")


The above DropDownList extension method simply creates the dropdown list's HTML markup needed to render a dropdown list with the list of application types returned and populated to the ViewBag.ApplicationTypes in step 1. The following are the parameters' values passed to the method:

  1. <strong>string name</strong>: The name of the dropdown list that will be used in the rendered HTML markup, and will represent both the ID and the name of the HTML element. In this case, "ApplicationType" is the dropdown list name.
  2. <strong>IEnumerable<SelectListItem> selectList</strong>: the enumerable type that the dropdown list will understand and is considered the connection point between the enumerable list created in step 1 and the expected enumerable list that the drop-down list expects. The SelectList class instance can be used in this case to supply the needed list along with identifying which property of your model will represet the dropdown list value and which will represent the text. The SelectList class constructor overload used in this case uses the following parameters:
    1. <strong>IEnumerable items</strong>: the enumerable list you created in step 1. In this case ViewBag.ApplicationTypes.
    2. <strong>string dataValueField</strong>: the string that will represent the model property that will be used as a dropdown list option value. In this case, "Id" (note that it matches the Id Property in the ApplicationTypeModel in step 1).
    3. <strong>string dataTextField</strong>: the string that will represent the model property that will be used as a dropdown list text value. In this case, "ApplicationName" (note that it matches the ApplicationName property in the ApplicationTypeModel in step 1).
    4. For more information about the SelectList class, please visit: MSDN: SelectList Class
  3. <strong>string optionLabel</strong>: the option that has no value, that the dropdown will be initially rendered with it selected. In this case, "- Select Type -"

For more information about the above Razor syntax of the DropDownList, please visit: MSDN: SelectExtensions.DropDownList Method.

The rendered HTML5 Markup in the above example should look like the following:

And the dropdown should look like the following screenshot:


Using the DropDownListFor

When you are building an HTML form in MVC and the view is bound to a model, there are a lot of cases where you would have a foreign key ID inside that model that you would like to build a dropdown list for in the form. DropDownListFor does that for you, where you can pass a predicate that will select the target property that will be populated with the user selection from the dropdown list. The following code snippet shows the Razor syntax for using the DropDownListFor:

@Html.DropDownListFor(model => model.ApplicationType, new SelectList(ViewBag.ApplicationTypes, "Id", "ApplicationName"), " - Select Type - ")


The above syntax is close to the Razor syntax using the, and DropDownList  it renders an HTML select element that is also close to the previous example except that the name and the ID of the rendered element will match the selected property in the predicate, which is "ApplicationType" in this case. 

Which means once the form is submitted, the user selected value of the dropdown list will be populated to the model property "ApplicationType".

The rendered dropdown list will look like the following example

One more benefit of using the strongly-typed DropDownListFor is the out-of-the-box model validation binding. If the model property is required, for example, then the form will not be submitted until an option is selected other than the "- Select Type -". 

The DropDownList extension method will provide the same behavior too, but you will have to make sure that the first parameter "name" matches exactly the target model property which is error-prone due to unexpected typos or a non-matching name could be supplied.

For more information about the DropDownListFor extension method, please visit MSDN: SelectExtensions.DropDownListFor Method (HtmlHelper, Expression, IEnumerable, Object)

Changing the dropdown list selected value programmatically (if needed)

There are real life scenarios where a developer may want to allow changing the dropdown list selected item programmatically, and it's absolutely possible to do so with the dropdown list. 

We will just do a few changes to the ViewBag assignment in the controller, and we will have a complete control over changing the selected value. The change that we need to do is very simple, which is instead of assigning a list to the ViewBag.ApplicationTypes  will assign the SelectList instance instead. 

I will explain the reason behind this soon. Now let's get back to the controller and change the ViewBag.ApplicationTypes line of code to be like the following:

SelectList selectList = new SelectList(_SectionAPI.GetAllApplicationTypes(), "Id", "ApplicationName", "- Type -"); ViewBag.ApplicationTypes = selectList;


And, of course, in the view we must change the DropDownListFor (or the DropDownList) Razor syntax to comply with that change:

@Html.DropDownListFor(model => model.ApplicationType, ViewBag.ApplicationTypes as SelectList, " - Select Type - ")


As you notice that the ViewBag.ApplicationTypes with a cast to SelectList was sufficient because we already created the SelectList in the action and passed it to the ViewBag.ApplicationTypes.

The reason we did this is that changing the dropdown list selected value is done through the SelectList items, so you can now do your business logic based on which the decision of changing the selected item would be taken then change the selected item using the following couple of lines of code:

SelectListItem item = selectList.FirstOrDefault(i => i.Value == "your value"); item.Selected = true;


In the first line the item to be selected is queried through a LINQ statement using the FirstOrDefault method (in case multiple items are found the first would be selected) then the item is selected in the second line using the Selected property.

Putting it all together

The following code snippet is how it should look like in your controller:





Note: As mentioned earlier, you should add some logic based on which the right selected value string would be returned to replace the "your value".


Step 2 Achievement: Once you complete this step you will have your dropdown list ready, up and running on the HTML page and once the form is submitted the value of the dropdown list will be populated to the selected model property either through DropDownList or DropDownListFor.

Step 3: Using Bootstrap for better-looking responsive DropDownList UI

As you might have noticed in step 2, the resulting dropdown list does not look so good, and it needs some UI tweaks so instead of digging deeply in HTML5 and CSS3, a great responsive framework is used to render a better looking responsive dropdown with the least effort possible.

For more information about the Bootstrap Framework, Please visit: http://getbootstrap.com/

Now, to do the Bootstrap magic, you are only required to do two extremely simple steps:

  1. Include the Bootstrap JS and CSS libraries to your view, In this case they are "bootstrap.min.css" and "bootstrap.min.js".
  2. Add a built-in CSS class to the dropdown markup which is "form-control" as shown in the following Razor snippet.

The following DropDown list Razor is the final syntax:

@Html.DropDownList("ApplicationTypes", new SelectList(ViewBag.ApplicationTypes, "Id", "ApplicationName"), " - Select Type - ", new { @class = "form-control" })


Notice the added new {@class = "form-control"} to include the mentioned Bootstrap CSS class. The dropdown list should look like the following now:


Useful examples

The following video shows a close example to how the above 3 steps are done and I encourage you to watch it


Conclusion

ASP.NET MVC allows creating dropdown lists in just a very simple 2-steps procedure. In the first step you will prepare the dropdown list data source and in the second one you will build the Razor syntax and configure the dropdown list options. 

You can also additionally improve the dropdown list UI to a better looking one and responsive using Bootstrap framework that will only require adding a CSS class to the dropdown list, and you will be completely set.

I hope this post was helpful and easy to follow and understand. Feel free to post your comments and questions and I will reply to them as soon as possible.

Did you find this helpful?

Read Next

The following articles are related to create modern asp.net mvc dropdown lists - 3 steps.

Create Modern ASP.NET MVC Dropdown Lists - 3 Steps
Fady Soliman
Fady SolimanMember since
Jun 22, 2013
Loading...
1 Comment

very good and helpfull article. thanks for this! :)

Contact Us
Share your COMMENT!

Share your thoughts and feedback on Create Modern ASP.NET MVC Dropdown Lists - 3 Steps

Ask any questions directly to Fady Soliman and the community!

By using this channel you approve that you agree on our Terms and Conditions