问题
Can you please help with the error below? What is wrong with my codes. Thanks for your help.
Error:
The ViewData item that has the key 'CategoryId' is of type 'System.Int32' but must be of type 'IEnumerable'.
controller
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);
view:
@(Html.DropDownListFor(x => x.CategoryId, (IEnumerable<SelectListItem>)ViewBag.Categories))
<br />
@Html.ValidationMessageFor(x => x.CategoryId)
回答1:
I have just populated viewbag again in post action of create, and it is solved.
来源:https://stackoverflow.com/questions/25919599/the-viewdata-item-that-has-the-key-categoryid-is-of-type-system-int32-but-mu