A "Formattable" SelectList for .NET MVC

It would be nice to be able to format the output of .NET MVC’s SelectList. For instance, recently I needed to format DateTime values in a SelectList in a more human-friendly way (e.g. Wednesday, November 16, 2011 3:00 PM).

What I’d like to be able to do is something like this:

@Html.DropDownFor(
  o => o.SomeProperty,
  new SelectList(ViewBag.MyItems, "ID", "Time", "{0:f}"),
  "Choose a Time"
)

Notice the format string as the fourth parameter in the SelectList. It would be ideal if you could pass in a format string as a parameter like this and have all of the values in your drop down formatted accordingly.

So I dug through the .NET source code a little bit and wrote up a FormattableSelectList class. It takes the same parameters as SelectList, except it also accepts a format string, like in the example above.

Unfortunately most of the code in MultiSelectList.cs (the base class of SelectList) is private, so I had to do some copy-and-paste duplication. It’s not as elegant under the hood as I would have liked, but it works. I essentially just overrode GetEnumerator, making sure to return SelectListItems whose Text properties were formatted. Here’s the c# source code: FormattableSelectList.cs

About these ads

2 thoughts on “A "Formattable" SelectList for .NET MVC

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s