Why Html.DropDownListFor requires extra cast?

Posted by dcompiled on Stack Overflow See other posts from Stack Overflow or by dcompiled
Published on 2010-06-11T23:09:32Z Indexed on 2010/06/11 23:12 UTC
Read the original article Hit count: 672

Filed under:
|
|
|
|

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"])

© Stack Overflow or respective owner

Related posts about c#

Related posts about asp.net-mvc