vote up 0 vote down
star

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

flag
add comment

3 Answers:

vote up 0 vote down
check

After a bunch of hemming and hawing it boils down to the following line of code

if (ViewData.ModelState.TryGetValue(key, out modelState))

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:

<%= Html.TextBox("MyTextBox", ViewData.Model.MyTextBox) %>
link|flag
comments (2)
vote up 0 vote down

I think I've seen this before. try:

return View(model, ViewData);

never mind. was thinking of something else. This obviously doesn't compile

link|flag
comments (2)
vote up 0 vote down

try setting the selected value in the controller action when creating the SelectList collection.

ViewData["AddressTypeId"] = new SelectList(CustomerService.AddressType_List(), "AddressTypeId", "Name", myItem.AddressTypeId);

link|flag
add comment

Your Answer:

Get an OpenID
or

Not the answer you're looking for? Browse other questions tagged or ask your own question.