Search code examples
c#asp.net-mvcenumshtml-helperviewdata

Why Html.DropDownListFor requires extra cast?


In my controller I create a list of SelectListItems and store this in the ViewData. When I read the ViewData in my View it gives me an error about incorrect types. If I manually cast the types it works but seems like this should happen automatically. Can someone explain?

Controller:

enum TitleEnum { Mr, Ms, Mrs, Dr };
var titles = new List<SelectListItem>();
foreach(var t in Enum.GetValues(typeof(TitleEnum)))
  titles.Add(new SelectListItem() 
    { Value = t.ToString(), Text = t.ToString() });

ViewData["TitleList"] = titles;

View:

// Doesn't work
Html.DropDownListFor(x => x.Title, ViewData["TitleList"])

// This Works
Html.DropDownListFor(x => x.Title, (List<SelectListItem>) ViewData["TitleList"])

Solution

  • Because ViewData is a Dictionary<string, Object>. How else could you store objects of multiple types in a keyed collection? Anything retrieved from ViewData without casting will be treated by the compiler as a base Object.