The ViewData item that has the key 'CategoryId' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.

白昼怎懂夜的黑 提交于 2019-12-24 16:55:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!