Why Html.DropDownListFor requires extra cast?
- by dcompiled
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"])