Niggles with ViewData and the Html.DropDownList

Posted on January 1, 2012

Just a quick post, to serve as reference to my future self.

There is a weird niggle that catches me at least once every 6 weeks when using ViewData to populate an Html.DropDownList in a view. Here is the simple example that cost me 30 minutes this morning

List<SelectListItem> months = new List<SelectListItem>();

for (int i = 1; i < 13; i++)
{
    months.Add(new SelectListItem()
    {
    Text = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i),
    Value = i.ToString(),
    Selected = (i == defaultMonth)
    });
}

ViewData["months"] = months;

As you can see, nothing special, I’m looping through months and adding them to a list of SelectListItems that get put into ViewData. There is one variable not shown, an int called defaultMonth that is going to be the lists selected item. On my View I have the following code.

@Html.DropDownList("months", (IEnumerable<SelectListItem>)ViewData["months"])

Its a simple one liner that creates a drop down based on my list, nothing special about it, we’ve all done something similar hundreds of times. Except that this will never ever ever show the list with your selected value, it will always show the first item. If you look at the values in debug as they are getting put into viewdata, everything is correct, and the value you want is the only value with selected set to true.

But the view will ignore it. Until you change the name of the Html.DropDownList so that it DOESN’T match the ViewData key you’re using to populate the list.

@Html.DropDownList("monthsDD", (IEnumerable<SelectListItem>)ViewData["months"])

Thats my working code….

*sigh*

 

Categories: Asp.net MVC


Leave a Reply