A Better ToSelectListItems

What I needed: Select lists in my ASP.NET MVC app where the options are created from data.
Suppose you have a State class and an IEnumerable of states in your ViewModel that end up looking something like so:

publicclassState

{

publicstringName { get; set; }

publicintStateId { get; set; }

}

publicclassAddressViewModel

{

publicIEnumerable<State> StateList { get; set; }

publicintSelectedStateId { get; set; }

}

(What’s the reference to State doing up in my viewModel? We’ll fix that)

a) I don’t want my ViewModel and Controller to have a dependency on System.Web.Mvc.

b) I want to choose the ‘selected’ option later, in the view. Why? Because what do you do if you have Two drop-downs that use the same data? State is a perfect example. Billing Address and Shipping Address will both use the same list, and I don’t want to have two copies of SelectListItem enumerables just so that they can have two different states “selected”.

c) I wanted an easy way to conditionally add a blank option at the top.

d) I wanted even MORE type safety. (with the ToSelectListItems extension method, you have to call ‘ToString’ on the Value everytime, which leads me to my next reason)

5 responses to “A Better ToSelectListItems”

Now if you can separate the concerns of “getting the data” and “choosing the presentation control” you’ll be able to test the item conversion with unit tests and only need UI tests to verify the existence of the control.

For example, if you have a convention for binding SelectedXId to XList then the UI can be simplified to:

Model.DropDownListFor(x=>x.SelectedStateId)

And you could still add blanks at the top with an extension like:

.WithDefault(“”)

This also allows you (or a non-coder) to easily change the display control to something else because getting the data into the right format isn’t the concern of the UI code anymore.