2014-09-18 103 views
1

你能幫忙解決下面的錯誤嗎?我的代碼有什麼問題。謝謝你的幫助。具有鍵'CategoryId'的ViewData項目類型爲'System.Int32',但必須是'IEnumerable <SelectListItem>'類型。

錯誤:

具有關鍵「CATEGORYID」的類型爲「System.Int32」,但必須是類型「的IEnumerable」的ViewData的項目。

控制器

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) 
+0

聽起來像一個重複的問題檢查這個以確保http://stackoverflow.com/questions/23293042/mvc-error-is-of-type-system-int32-but-must-be-of-type-ienumerableselectlist – MethodMan 2014-09-18 18:19:24

回答

1

我剛纔在創建後再次行動填充viewbag,並就解決了。

相關問題