Working with drop-down lists in ASP.NET MVC has some confusing aspects, so let’s look at an example.
Imagine the goal is to edit a song (not the music and lyrics of a song – just the boring data pieces). Each song is associated with an album, and each song has a title and track number. With this description, you can imagine an edit view using the following code:
<%= Html.DropDownList("AlbumId", Model.Albums)%> ... <%= Html.TextBox("Title", Model.Title) %> ... <%= Html.TextBox("TrackNumber", Model.TrackNumber) %>
The Html.DropDownList helper method likes to work with SelectListItem objects, so a view model you can pair with this view looks like the following:
public class EditSongViewModel { public string Title { get; set; } public int TrackNumber { get; set; } public IEnumerable<SelectListItem> Albums { get; set; } }
Some people don’t like to use SelectListItem types in their view models. Instead, they’ll convert to them in the view. I think it’s entirely reasonable to use SelectListItem in a view model, because the view model is supposed to make the view easier to write. Having the view model perfectly aligned with the needs of the view means you need to think less (and write less code) when creating the view.
There are a couple approaches you can take when creating a sequence of SelectListItem objects. I think the cleanest approach is to have an extension method that knows how to take a collection of objects in your software (like Album objects), and map them into SelectListItem objects.
public static IEnumerable<SelectListItem> ToSelectListItems( this IEnumerable<Album> albums, int selectedId) { return albums.OrderBy(album => album.Name) .Select(album => new SelectListItem { Selected = (album.ID == selectedId), Text = album.Name, Value = album.ID.ToString() }); }
You can use the method like this:
model.Albums = _repository.FindAllAlbums().ToSelectItems(selectedId);
That code works, because Html.DropDownList will happily work with IEnumerable of SelectListItem.
The class you need to be careful with is the SelectList class. I’ve seen quite a few people make the mistake of wrapping their SelectListItem objects in a SelectList without setting the DataTextField and DataValueField properties. This does not work:
model.Albums = new SelectList( _repository.FindAllAlbums().ToSelectListItems(1) );
You’d think the SelectList class would know how to work with a collection of SelectListItem objects - but it doesn’t. The following doesn’t work either (the drop-down list will display “System.Web.Mvc.SelectListItem” for every entry):
model.Albums =
new SelectList(_repository.FindAllAlbums()
.ToSelectItems(selectedID));
The SelectList class is really designed to perform the conversion we did earlier (with the extension method), but it uses late binding reflection. The following would work, because we tell the SelectList where to find the text and value fields:
model.Albums = new SelectList( _repository.FindAllAlbums(), "ID", "Name" );
If you are using the same model to accept input from the edit view during a postback, you might think the default model binder will repopulate the Albums collection with all the album information and set the selected album. Unfortunately - the web doesn’t work this way and the Albums collection will be empty.
The only album related information the browser will post is the value of the selected item. If you want this value bound to a model, you’ll need to provide an AlbumId property (to match the name we gave the DropDownList in the view - “AlbumId”).
public class EditSongViewModel { public int AlbumId { get; set; } public string Title { get; set; } public int TrackNumber { get; set; } public IEnumerable<SelectListItem> Albums { get; set; } }
Some people will create two separate view models in this case. One view model is designed to carry information to the view, and will have an Albums property (but no AlbumId property). The second view model is designed to accept user input during postback and will have an AlbumId propery (but no Albums property). This approach adds the overhead of an extra class, but the view models are perfectly aligned with their duties and no properties go unused. You’ll have to decide which approach is best for you.
Comments
I have the extension method do a yield return with a blank SelectListItem, then return the rest of the items after a Select. I think it works out pretty well.
stackoverflow.com/...
Would it be possible to change over your extension so that any DB Table with an "Id" and "Name" layout could use it?
Thinking:
public static IEnumerable<SelectListItem> ToSelectListItems(
this IEnumerable<T> items, int selectedId) { //not sure of the rest }
Thanks :)
Nice article...
If you can create some sample code to download, would be great. I am new with MVC framework
Thanks
Just seems like you re-invented a wheel that was solved MANY MANY months ago.
Because it only saves one line of code, and doesn't explain to people why the collection isn't recreated on post back.
There is an example of this in my article on IFilterPriority with IJoinedFilter: geekswithblogs.net/...
I use this in conjunction with the MVCContrib fluent html syntax for creating a select or multi select list. This can be embedded in a template too, for reuse in the view.
public static class EnumerableHelpers
{
public static IList<SelectListItem> ToSelectItemList<T>(this IEnumerable<T> list, Func<T, string> textSelector, Func<T, string> valueSelector, IEnumerable<T> selected)
{
IList<SelectListItem> results = new List<SelectListItem>();
foreach (T item in list)
{
results.Add(new SelectListItem { Text = textSelector.Invoke(item), Value = valueSelector.Invoke(item), Selected = selected.Contains(item) });
}
return results;
}
public static IList<SelectListItem> ToSelectItemList<T>(this IEnumerable<T> list, Func<T, string> textSelector, Func<T, string> valueSelector)
{
return ToSelectItemList(list, textSelector, valueSelector, new List<T>());
}
}
the useage would be
Model.ListOfFoo.ToSelectItemList(foo => foo.PropertyToDisplay, foo => foo.ValueToSubmit);
scott - thanks for putting this article up in the 1st place - very timely.
cheers
jim
btw - here's the method that i have been using similar to your own:
public static List<SelectListItem> ToSelectList<T>(this IEnumerable<T> enumerable, Func<T, string> text, Func<T, string> value, string defaultOption)
{
var items = enumerable.Select(f => new SelectListItem() { Text = text(f), Value = value(f) }).ToList();
items.Insert(0, new SelectListItem() { Text = defaultOption, Value = "-1" });
return items;
}
"Extension methods must be defined in a non-generic static class"
public class ExperienceFormViewModel
{
private TigerDataContext db = new TigerDataContext();
ExperienceRepository expRepository = new ExperienceRepository();
// Properties
public EMP_EXPERIENCE empExperience { get; private set; }
public IEnumerable<SelectListItem> drpCountry { get; set; }
// Constructor
public ExperienceFormViewModel(EMP_EXPERIENCE eMP_EXPERIENCE)
{
empExperience = eMP_EXPERIENCE;
}
public static IEnumerable<SelectListItem> ToSelectListItems(this IEnumerable<MST_COUNTRY> mst_countrys, string selectedId)
{
return
mst_countrys.OrderBy(mst_country => mst_country.COUNTRY_NM)
.Select(mst_country =>
new SelectListItem
{
Selected = (mst_country.COUNTRY_ID == selectedId),
Text = mst_country.COUNTRY_NM,
Value = mst_country.COUNTRY_ID.ToString()
});
}
}