We found strange behaviour in DropDownListFor (ASP.NET MVC3 release). It selects ViewBag property value instead of Model property value in dropdown.
Model:
public class Country {
public string Name { get; set; }
}
public class User {
public Country Country { get; set; }
}
Controller Index action:
ViewBag.CountryList = new List<Country> { /* Dropdown collection */
new Country() { Name = "Danmark" },
new Country() { Name = "Russia" } };
var user = new User();
user.Country = new Country(){Name = "Russia"}; /* User value */
ViewBag.Country = new Country() { Name = "Danmark" }; /* It affects user */
return View(user);
View:
@Html.EditorFor(user => user.Country.Name)
@Html.DropDownListFor(user => user.Country.Name,
new SelectList(ViewBag.CountryList, "Name", "Name", Model.Country), "...")
It will show text box with “Russia” value and dropdown with “Danmark” value selected instead of “Russia”.
I didn’t find any documentation about this behaviour. Is this behaviour normal? And why is it normal? Because it is very hard to control ViewBag and Model properties names.
I’m not so sure why this decision was made, but it was happened because MVC framework tried to use the ViewData-supplied value before using the parameter-supplied value. That’s why
ViewBag.Countryoverride parameter-supplied valueModel.Country.That was how it was written in MVC framework in the private method
SelectInternal.This code
defaultValue = htmlHelper.ViewData.Eval(fullName);tried to get the value fromViewDataand if it can get the value, it will override the supplied parameterselectListwith new list.Hope it can help. Thanks.
side-node: ViewBag is just a dynamic wrapper class of ViewData.