The complete guide to creating modern drop down lists in ASP.NET MVC and Bootstrap

Create Modern ASP.NET MVC Dropdown Lists - 3 Steps
25 April, 2017
Fady Soliman
178 Views

Step 1: Creating the data source

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:

public class ApplicationTypeModel

{

public int Id { set; get; }

public string ApplicationName { set; get; }

}

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. string name: 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. IEnumerable<SelectListItem> selectList: 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 is uses the following parameters:
    1. IEnumerable items: the enumerable list you created in step 1. In this case ViewBag.ApplicationTypes.
    2. string dataValueField: 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. string dataTextField: 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. string optionLabel: 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:

<select id="ApplicationType" name="ApplicationType">

<option value=""> - Select Type - </option>

<option value="0">Forum</option>

<option value="1">Weblog</option>

<option value="2">Gallery</option>

<option value="3">GuestBook</option>

</select>

And the dropdown should look like the following screenshot:

DropDown list using MVC Razor


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 DropDownList and 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

<select id="ApplicationType" name="ApplicationType">

<option value=""> - Select Type - </option>

<option value="0">Forum</option>

<option value="1">Weblog</option>

<option value="2">Gallery</option>

<option value="3">GuestBook</option>

</select>

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 we will assign the SelectList instance instead. I will explain the reason behind this soon. Now lets 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

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

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

item.Selected = true;

ViewBag.ApplicationTypes = selectList;

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:

MVC Dropdownlist with Bootstrap and Razor



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.

Related Posts

24 April, 2017
Fady Soliman
web design , .net , css , kendo ui
178 Views

Did you find this helpfull?

About The Author

Fady Soliman

An experienced, resourceful and highly motivated IT professional, with a proven record of success in both Stack Development and Software Architecture. Possesses a wealth of transferable skills, including outstanding interpersonal, problem solving and staff management abilities. A capable organizer, quick to grasp – and make good use of – new ideas and information, and reliable and conscientious in all he takes on.

leave A Comment