OdeToCode IC Logo

Pretty Code #1 – Building SelectListItems

Friday, July 3, 2009

In ASP.NET MVC, you can use a collection of SelectListItems to help build an HTML

Tonight, you’ll be the judge in this first contest of charm, grace, and readability.

Contestant #1 hails from the System.Web.Mvc namespace. It likes pina coladas and string literals, but is turned off by tattoos that look like programming symbols. Let me introduce the SelectList class:

var products = GetProducts();
var selectItems = new SelectList(products, "ID", "Name");

Contestant #2 lives in the System.Linq namespace. It likes whips and method chains. Functional programmers call it “map”, but in .NET we call it "Select":

var selectItems = from product in GetProducts()
                  select new SelectListItem 
                  {
                      Text = product.Name,
                      Value = product.ID.ToString()
                  };

… or (from the backside) …
var selectList = GetProducts().Select(product =>
                    new SelectListItem
                    {
                        Value = product.ID.ToString(),
                        Text = product.Name 
                    });

Contestant #3 lives in the MvcContrib project. It’s turned on by pointy things and practices yoga for extensibility. Introducing the ToSelectList method:

var selectItems = GetProducts().ToSelectList(product => product.ID,
                                             product => product.Name);

Personally, I like #2. While the name of #3 makes its purpose obvious, it sometimes takes a moment to be 100% clear about what property becomes Text, and what property becomes Value. In #2 the Text and Value assignments are obvious, even though the code is a little longer. Setting the Selected properties with either approach is trivial.

What do you think?