Html.DropDownList and Html.ListBox in MVC

Both the DropDownList and ListBox helpers return a <select /> element. DropDownList allows single item selection, whereas ListBox allows for multiple item selection (by setting the multiple attribute to multiple in the rendered markup).
Typically, a select element serves two purposes:

  • To show a list of possible options
  • To show the current value for a field

In the Music Store, you have an Album class with a GenreId property. You are using the select element to display the value of the GenreId property, as well as all other possible categories.
There is a bit of setup work to do in the controller when using these helpers because they require some specifi c information. A list needs a collection of SelectListItem instances representing all the possible entries for the list. A SelectListItem object has Text, Value, and Selected properties. You can build the collection of SelectListItem objects yourself, or rely on the SelectList or MultiSelectList helper classes in the framework. These classes can look at an IEnumerable of any type and transform the sequence into a sequence of SelectListItem objects. Take, for example, the Edit action of the StoreManager controller:

public ActionResult Edit(int id)
{
var album = storeDB.Albums.Single(a => a.AlbumId == id);
ViewBag.Genres = new SelectList(storeDB.Genres.OrderBy(g => g.Name), "GenreId", "Name", album.GenreId);
return View(album);
}

You can think of the controller action as building not only the primary model (the album for editing), but also the presentation model required by the drop-down list helper. The parameters to the SelectList constructor specify the original collection (Genres from the database), the name of the property to use as a value (GenreId), the name of the property to use as the text (Name), and the value of the currently selected item (to determine which item to mark as selected).
If you want to avoid some refl ection overhead and generate the SelectListItem collection yourself, you can use the LINQ Select method to project Genres into SelectListItem objects:

public ActionResult Edit(int id)
{
var album = storeDB.Albums.Single(a => a.AlbumId == id);
ViewBag.Genres =
storeDB.Genres
.OrderBy(g => g.Name)
.AsEnumerable()
.Select(g => new SelectListItem
        	{
            	Text = g.Name,
Value = g.GenreId.ToString(),
            	Selected = album.GenreId == g.GenreId
});
return View(album);
}
Tagged . Bookmark the permalink.

Leave a Reply