Have just started playing with ASP.NET MVC and have stumbled over the following situation. It feels a lot like a bug but if its not, an explanation would be appreciated 🙂
The View contains pretty basic stuff
<%=Html.DropDownList('MyList', ViewData['MyListItems'] as SelectList)%> <%=Html.TextBox('MyTextBox')%>
When not using a model, the value and selected item are set as expected:
//works fine public ActionResult MyAction(){ ViewData['MyListItems'] = new SelectList(items, 'Value', 'Text'); //items is an ienumerable of {Value='XXX', Text='YYY'} ViewData['MyList'] = 'XXX'; //set the selected item to be the one with value 'XXX' ViewData['MyTextBox'] = 'ABC'; //sets textbox value to 'ABC' return View(); }
But when trying to load via a model, the textbox has the value set as expected, but the dropdown doesnt get a selected item set.
//doesnt work public ActionResult MyAction(){ ViewData['MyListItems'] = new SelectList(items, 'Value', 'Text'); //items is an ienumerable of {Value='XXX', Text='YYY'} var model = new { MyList = 'XXX', //set the selected item to be the one with value 'XXX' MyTextBox = 'ABC' //sets textbox value to 'ABC' } return View(model); }
Any ideas? My current thoughts on it are that perhaps when using a model, we’re restricted to setting the selected item on the SelectList constructor instead of using the viewdata (which works fine) and passing the selectlist in with the model – which would have the benefit of cleaning the code up a little – I’m just wondering why this method doesnt work….
Many thanks for any suggestions
After a bunch of hemming and hawing it boils down to the following line of code
which means MVC is trying to resolve the value by only looking at the ViewData Dictionary<> object and not traversing down into the ViewData.Model object.
Whether that’s a bug, limitation or design decision I’m not sure. However, you can fix it the following way: