Headaches with ASP.MVC UI Helpers

I’ve been beating my head against the UI helpers a lot lately and wanted to share a frustration point. Say I want to do something using the DropDownList, so you map a property on your page that returns a Select List:

<%= Html.DropDownList("db", SelectList)%>

        public static SelectList SelectList
                List<ListItem> items = new List<ListItem>
                                               new ListItem {Selected = true, Text = "All", Value = ""},
                                            new ListItem {Text = "Apples", Value = "Ap"},
                                            new ListItem {Text = "Bananas", Value = "Bn"},
                                            new ListItem {Text = "Oranges", Value = "Or"}
                return new SelectList(items);

Seems simple enough right? I’m giving the select list a list of ListItem. I’m using YOUR api. I don’t expect that THIS is what I get back:

Looks like you’re assuming that I won’t use your list of items:

        [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate",
            Justification = "Operation performs conversions and returns a unique instance on each call.")]
        public virtual IList<ListItem> GetListItems() {
            return (!String.IsNullOrEmpty(DataValueField)) ?
                GetListItemsWithValueField() :

Perhaps a check to see if the items in the enumerable ARE already LISTITEM would be appropriate?

For the record, changing it to this makes the code work:

return new SelectList(items, "Value", "Text", items[0]);

But what happened to convention over configuration?

Edit: ok, the “correct” way I posted wasn’t actually correct. You can’t put the “Selected” item in the selectedValue field, you have to put the value there, in this case “Bn” or “Ap” etc. Heaven forbit putting the actual selected item as the parameter. Or pulling the selected item automatically from request values.

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>