1
你能帮忙解决下面的错误吗?我的代码有什么问题。谢谢你的帮助。具有键'CategoryId'的ViewData项目类型为'System.Int32',但必须是'IEnumerable <SelectListItem>'类型。
错误:
具有关键“CATEGORYID”的类型为“System.Int32”,但必须是类型“的IEnumerable”的ViewData的项目。
控制器
public ActionResult ProductCreate()
{
ViewBag.Suppliers = db.Suppliers.Where(x => x.IsActive).ToList();
ViewBag.Categories = new SelectList(db.Categories.Where(x => x.IsActive).ToList(), "Id", "Name").ToList();
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ProductCreate(Product product, int[] suppliers)
{
if (ModelState.IsValid)
{
foreach (int SupplierId in suppliers)
{
product.Suppliers.Add(db.Suppliers.Find(SupplierId));
}
db.Products.Add(product);
db.SaveChanges();
return RedirectToAction("ProductIndex");
}
return View(product);
观点:
@(Html.DropDownListFor(x => x.CategoryId, (IEnumerable<SelectListItem>)ViewBag.Categories))
<br />
@Html.ValidationMessageFor(x => x.CategoryId)
听起来像一个重复的问题检查这个以确保http://stackoverflow.com/questions/23293042/mvc-error-is-of-type-system-int32-but-must-be-of-type-ienumerableselectlist – MethodMan 2014-09-18 18:19:24