Tuesday, September 8, 2009

Code: ASP.Net MVC SelectList / DropDownList Selected Item

I spent an hour on a strange issue on my MVC page the other day where MVC would not obey my SelectedItem assignment on a drop down list.  I originally thought the issue was how I was making the assignment in code, or the object I was using to do the binding, but it turns out that some built in MVC functionality was actually working against me.  If you name your ViewData key name the same name as your Html.DropDownList item, MVC will attempt to populate the selected value for you.  However I wanted to manually set the selected value so my solution was to change this:
<%= Html.DropDownList("Encoding", ViewData["Encoding"] as SelectList)%>

<%= Html.DropDownList("Encoding", ViewData["EncodingData"] as SelectList)%>

And in my controller I just needed to change the ViewData key name accordingly:
Dictionary<string, string> pushPull = new Dictionary<string, string>();
pushPull.Add("pull_encode", "Pull");
pushPull.Add("push_encode", "Push");
if (pushPullValue == "") pushPullValue = "pull_encode";
ViewData["EncodingData"] = new SelectList(pushPull, "Key", "Value", pushPullValue);