【发布时间】:2016-03-25 19:02:43
【问题描述】:
我有以下视图模型
public class ProjectVM
{
....
[Display(Name = "Category")]
[Required(ErrorMessage = "Please select a category")]
public int CategoryID { get; set; }
public IEnumerable<SelectListItem> CategoryList { get; set; }
....
}
和下面的控制器方法创建一个新的项目并分配一个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:具有键“CategoryID”的 ViewData 项属于“System.Int32”类型,但必须属于“IEnumerable
”类型。
使用@Html.DropDownList() 方法会发生同样的错误,如果我使用ViewBag 或ViewData 传递SelectList。
【问题讨论】:
标签: c# asp.net-mvc