具有键“XXX”的ViewData项的类型为“System.Int32”
我有以下视图模型
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 <SelectListItem>”类型。
使用该@Html.DropDownList()方法会发生相同的错误,如果我使用ViewBag或传递SelectList ViewData。
慕后森
MMTTMM
墨色风雨
慕田峪7331174
随时随地看视频慕课网APP