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
Thank You!
Absolutely. Hope it’s helpful.