【发布时间】:2013-12-04 09:47:41
【问题描述】:
这是我在 MultiSelectList 中显示名称列表的代码
控制器
// GET
public ActionResult Create()
{
var bookViewModel = new BookViewModel
{
AuthorList = _Authors.GetAuthors()
.Select(a => new SelectListItem {
Value = a.Id.ToString(),
Text = a.Name }
).ToList()
};
return View(bookViewModel);
}
// POST
[HttpPost]
public ActionResult Create(BookViewModel model)
{
if (ModelState.IsValid)
{
//Some code
}
else
{
return View(model);
}
}
查看
@using (Html.BeginForm())
{
...
@Html.ListBoxFor(m => m.AuthorIds, Model.AuthorList, new { multiple = "multiple" })
<input id="btnCreate" type="submit" value="Create" />
}
如果模型验证,此代码工作正常,但如果 ModelState.IsValid = false,当它将模型返回到视图 (.. else { return View(model); }) 时,模型不包含 AuthorList 并显示错误
没有“IEnumerable”类型的 ViewData 项 有键“AuthorIds”。
在视图行@Html.ListBoxFor(m => m.AuthorIds, Model.AuthorList....
知道如何解决这个问题吗?
【问题讨论】:
标签: c# razor data-binding multi-select asp.net-mvc-5