【发布时间】:2011-07-27 15:51:58
【问题描述】:
我们在 DropDownListFor(ASP.NET MVC3 版本)中发现了奇怪的行为。它在下拉列表中选择 ViewBag 属性值而不是 Model 属性值。
型号:
public class Country {
public string Name { get; set; }
}
public class User {
public Country Country { get; set; }
}
控制器索引操作:
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);
查看:
@Html.EditorFor(user => user.Country.Name)
@Html.DropDownListFor(user => user.Country.Name,
new SelectList(ViewBag.CountryList, "Name", "Name", Model.Country), "...")
它将显示带有“俄罗斯”值的文本框和选择“丹麦”值而不是“俄罗斯”的下拉菜单。
我没有找到有关此行为的任何文档。这种行为正常吗?为什么是正常的?因为很难控制 ViewBag 和 Model 属性名称。
【问题讨论】:
标签: asp.net-mvc-3