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.

public class ContactsController : Controller
{
    private ContactDbContext db = new ContactDbContext();

    // GET: Contacts
    public ActionResult Index()
    {
        var contacts = from c in db.Contacts
                       select c;
        return View(contacts);
    }
}

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.

var cityList = new List<string>();
var cityDistinct = from c in db.Contacts
                   orderby c.City
                   select c.City;

cityList.AddRange(cityDistinct.Distinct());
ViewBag.city = new SelectList(cityList);

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.

public ActionResult Index(string city)
{
    var cityList = new List<string>();
    var cityDistinct = from c in db.Contacts
                       orderby c.City
                       select c.City;

    cityList.AddRange(cityDistinct.Distinct());
    ViewBag.city = new SelectList(cityList);

    var contacts = from c in db.Contacts
                   select c;

    if (!string.IsNullOrWhiteSpace(city))
    {
        contacts = contacts.Where(c => c.City == city);
    }

    return View(contacts);
}

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

@using (Html.BeginForm("Index", "Contacts", FormMethod.Get))
{
<p>
    City: @Html.DropDownList("city", 
                             ViewBag.city as SelectList, 
                             "All", 
                             new {@class = "city", 
                                  onchange = "this.form.submit();"})
</p>
}

“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

Add a Dropdown Filter Read More »