Add a Dropdown Filter

On my contacts application I wanted the option to only show contacts from a specific city. To accomplish this I am going to use a dropdown with a distinct list of cities that exist in my contact list.

Below is part of the existing contacts controller with the Index action that gets all contacts and returns a view.

Using ContactDbContext, which is a entity framework DbContext for contacts, the database will be queried for a list of distinct cities. The list of distinct cities is then stored as a select list in the view bag.

ViewBag is a dynamic object and is one way to pass data from a controller to a view. A dynamic object basically allows you to add properties just by setting them. In the above example the with ViewBag.city is adding a city property to the ViewBag and setting it equal to a new SelectList.

The resulting index action now takes a city parameter which is used when querying for contact if it has a value.

In my razor view the following adds the new city filter to the UI.

“All” is the label used for the default empty item. The last bit is for HTML attributes and set the class for the drop down to “city” and makes it so the form submits on change of the drop down. This means that when a new city is selected the view will refresh and only show contacts for the newly selected city.

This is the resulting UI:CityFilterUi