最佳答案
我有以下视图模型
public class ProjectVM
{
....
[Display(Name = "Category")]
[Required(ErrorMessage = "Please select a category")]
public int CategoryID { get; set; }
public IEnumerable<SelectListItem> CategoryList { get; set; }
....
}
以及下面的控制器方法,以创建一个新的 Project 并分配一个 Category
public ActionResult Create()
{
ProjectVM model = new ProjectVM
{
CategoryList = new SelectList(db.Categories, "ID", "Name")
}
return View(model);
}
public ActionResult Create(ProjectVM model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Save and redirect
}
在风景里
@model ProjectVM
....
@using (Html.BeginForm())
{
....
@Html.LabelFor(m => m.CategoryID)
@Html.DropDownListFor(m => m.CategoryID, Model.CategoryList, "-Please select-")
@Html.ValidationMessageFor(m => m.CategoryID)
....
<input type="submit" value="Create" />
}
视图显示正确,但是在提交表单时,我得到以下错误消息
InvalidOperationException: 键值为“ Category oryID”的 ViewData 项属于“ System. Int32”类型,但必须属于“ IEnumable < SelectListItem >”类型。
如果我使用 ViewBag
或 ViewData
传递 SelectList,也会发生同样的错误。