Well... probably you mistyped some variable name, but this was not the real problem.
You must tell the SelectList how to bind the list and which property of the object is used for the text and which for the data, so, since each element in the dictionary is a KeyValuePair the controller should be:
public ActionResult SelectSample()
{
var dict = new Dictionary<string, string>();
dict.Add("Blank", "_blank");
dict.Add("Parent", "_parent");
dict.Add("Self", "_self");
dict.Add("Top", "_top");
ViewData["Targets"] = new SelectList(dict,"Value","Key");
return View();
}
Then the DropDownList can also be called with the easy overload:
<%= Html.DropDownList("","Targets") %>
The easy overload automatically probes both the ViewData dictionary and the model, so no need to do all the conditional binding you are doing in your code.
simonech
Member
344 Points
136 Posts
MVP
Re: DropDownList ... What am I doing wrong?
Sep 15, 2008 11:34 PM|LINK
Well... probably you mistyped some variable name, but this was not the real problem.
You must tell the SelectList how to bind the list and which property of the object is used for the text and which for the data, so, since each element in the dictionary is a KeyValuePair the controller should be:
public ActionResult SelectSample() { var dict = new Dictionary<string, string>(); dict.Add("Blank", "_blank"); dict.Add("Parent", "_parent"); dict.Add("Self", "_self"); dict.Add("Top", "_top"); ViewData["Targets"] = new SelectList(dict,"Value","Key"); return View(); }Then the DropDownList can also be called with the easy overload:
The easy overload automatically probes both the ViewData dictionary and the model, so no need to do all the conditional binding you are doing in your code.
HTH
Simo