このエラーが発生します
There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'CategoryList'.
私はこの問題に関するstackoverflowの他のすべての投稿を読みましたが、修正できません!まったく同じことを行うテストmvc3プロジェクトを作成したので、問題なく動作するはずです。
コントローラコードは次のとおりです。
public ViewResult EditProduct(Guid id)
{
var product = _repository.Products.FirstOrDefault(x => x.ID == id);
ViewBag.CategoryList = _repository.Categories.Select(x => new SelectListItem { Text = x.Name, Value = x.ID.ToString(), Selected = productToEdit.ID == x.ID }) as IEnumerable<SelectListItem>;
return View(product);
}
[HttpPost]
public ActionResult EditProduct(Product productToEdit)
{
ViewBag.CategoryList = _repository.Categories.Select(x => new SelectListItem { Text = x.Name, Value = x.ID.ToString(), Selected = productToEdit.ID == x.ID }) as IEnumerable<SelectListItem>;
if (ModelState.IsValid)
{
_repository.SaveProduct(productToEdit);
TempData["message"] = string.Format("{0} has been saved", productToEdit.Title);
return RedirectToAction("Product");
}
return View(productToEdit);
}
かみそりのコードは次のとおりです。
<span class="field">
@Html.DropDownList("CategoryList");
</span>
私も試しました:
<span class="field">
@Html.DropDownList("CategoryList", ViewBag.CategoryList as IEnumerable<SelectListItem>);
</span>
ちなみに、<span>
は内部AjaxBeginForm
にあり、モデルへの他の呼び出しも同様に含まれています。
CategoryListの前に_0を付けてみました。それも問題にはならないはずです。私のテストプロジェクトはリストを必要としないので、リストをキャストする2番目のパラメータータイプを用意する必要さえないことを私は知っています。ViewModelを使用する必要がないことはわかっています。これも機能するはずであり、MvcMusicStoreは機能していることを示しています。
一体なぜそれは私を動かさないのですか?
助けてくれてありがとう、私が理解しやすいようにサンプルコードをいただければ幸いです。
ありがとう、