本文介绍了具有键"CategoryId"的ViewData项目的类型为"System.Int32",但必须类型为"IEnumerable< SelectListItem>".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
能否请您解决以下错误?我的代码有什么问题.感谢您的帮助.
Can you please help with the error below? What is wrong with my codes. Thanks for your help.
错误:
具有键"CategoryId"的ViewData项的类型为"System.Int32",但必须类型为"IEnumerable".
The ViewData item that has the key 'CategoryId' is of type 'System.Int32' but must be of type '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)
推荐答案
我刚刚在create的后期操作中再次填充了viewbag,并且已解决.
I have just populated viewbag again in post action of create, and it is solved.
这篇关于具有键"CategoryId"的ViewData项目的类型为"System.Int32",但必须类型为"IEnumerable< SelectListItem>".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!