【发布时间】:2014-11-13 04:52:43
【问题描述】:
您能帮忙解决以下错误吗?我的代码有什么问题。感谢您的帮助。
错误:
具有“CategoryId”键的 ViewData 项属于“System.Int32”类型,但必须属于“IEnumerable”类型。
控制器
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)
【问题讨论】:
-
听起来像一个重复的问题检查这个以确保stackoverflow.com/questions/23293042/…
标签: c# ienumerable dropdownlistfor selectlistitem