Magic strings are just nuclear-powered bug magnets. They attract fat-fingering mistakes while coding and practically guarantee bugs will be introduced while refactoring. If you’re like me, you’ll hate the magic strings required in the Html.DropDownListFor as much as I do. Now there’s an easy way to get rid of them once and for all…


These extension methods attached to lists clean up your drop down list code and make them refactor-resistant:

public static IEnumerable ToSelectList(this IEnumerable items, Func value, Func text, object selectedValue)
        {
            return items.Select(item => new SelectListItem
                                            {
                                                Text = text(item),
                                                Value = value(item),
                                                Selected = (selectedValue != null)?(selectedValue.ToString() == value(item)):false
                                            });
        }

This overload eliminates some extra typing for drop down lists that don’t need a selected item:

public static IEnumerable ToSelectList(this IEnumerable items, Func value, Func text)
        {
            return items.ToSelectList(value, text, null);
        }

Now your drop down list code is simplified and refactor-safe, behold!

Html.DropDownListFor(x => x.MyId, Model.MyItems.ToSelectList(x => x.MyValue, x => x.MyText, Model.MyId))

« »