【问题标题】:The ViewData item that has the key 'CategoryId' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.具有键“CategoryId”的 ViewData 项属于“System.Int32”类型,但必须属于“IEnumerable<SelectListItem>”类型。
【发布时间】: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)

【问题讨论】:

标签: c# ienumerable dropdownlistfor selectlistitem


【解决方案1】:

我刚刚在创建的后期操作中再次填充了 viewbag,它已经解决了。

【讨论】:

    猜你喜欢
    • 2016-03-25
    • 2016-03-21
    • 2023-03-12
    • 2018-07-24
    • 1970-01-01
    • 2012-01-25
    相关资源
    最近更新 更多