我有代码:
<%: Html.DropDownListFor(
model => model.CompanyName,
new SelectList(ViewData["ActiveCompanies"] as IEnumerable,
"Id", "Name"))
%>
列表正在填充名称等,但是所选项目名称没有绑定到Model.CompanyName(如果解决方案返回id就可以了,所以我可以使用
<%: Html.DropDownListFor(
model => model.CompanyID,
new SelectList(ViewData["ActiveCompanies"] as IEnumerable,
"Id", "Name"))
%>
事实上这对我的目的来说会更好,但如果我能找出数据未被绑定的原因,那将会非常有用。
答案 0 :(得分:5)
html助手总是根据value属性绑定数据,而不是文本。也不要使用ViewData和强制转换。我建议你这样做:
<%: Html.DropDownListFor(model => model.CompanyID,
new SelectList(Model.ActiveCompanies, "Id", "Name")) %>
在控制器中填充ActiveCompanies
属性:
public ActionResult Index()
{
var model = new SomeViewModel
{
// TODO: Use a repository
ActiveCompanies = new[]
{
new Company { Id = 1, Name = "Company 1" },
new Company { Id = 2, Name = "Company 2" },
new Company { Id = 3, Name = "Company 3" },
}
}
return View(model);
}