ASP.NET MVC DropDownListForエラー:タイプMISMATCH
でを使用するときに遭遇した共通点について説明します。
InvalidOperationException
DropDownListFor
問題:"The ViewData item that has the key 'XXX' is of type 'System.Int32' but must be of type 'IEnumerable'."
)にバインドされているときに発生します。 ヘルパーは、選択したアイテムを表す単一の整数値ではなく、選択可能なアイテムのコレクションを期待しています。
原因:XXX
DropDownListFor
フォームの提出が単一の整数値(選択したID)を提供するために不一致が発生しますが、ヘルパーはドロップダウンオプションを埋めるためにコレクションを必要とします。
int
IEnumerable<SelectListItem>
例のシナリオ:DropDownListFor
カテゴリIDのプロパティを備えたモデルがあるとしましょう。 および
:を使用したビュー
フォームの提出時に、には選択した整数IDのみが含まれ、エラーが発生します。
解決策:int
public class ProjectVM { public int CategoryID { get; set; } }
次に、コントローラーにこのDropDownListFor
プロパティを入力します:
@Html.DropDownListFor(model => model.CategoryID, new SelectList(ViewBag.Categories, "ID", "Name"))
あなたのビューは次のことを使用します:CategoryID
重要な考慮事項:
public class ProjectVM { public int CategoryID { get; set; } public IEnumerable<SelectListItem> CategoryList { get; set; } }
非常に重要なことに、CategoryList
アクションメソッドで
public class HomeController : Controller { public ActionResult Create() { var model = new ProjectVM(); model.CategoryList = new SelectList(db.Categories, "ID", "Name"); // Assuming db is your database context return View(model); } [HttpPost] public ActionResult Create(ProjectVM model) { if (ModelState.IsValid) { // Save model to database } // Repopulate the CategoryList in case of validation errors model.CategoryList = new SelectList(db.Categories, "ID", "Name"); return View(model); } }
@Html.DropDownListFor(model => model.CategoryID, Model.CategoryList)
カテゴリの実際のデータソースに置き換えます。 およびプロパティがデータベーススキーマと一致することを確認してください。
CategoryList
ヘルパーに必要なアイテムのコレクションを提供し、タイプの不一致エラーを解決します。以上がなぜ私のドロップダウンリストは、キー「xxx」を搭載した「viewdataアイテム」がタイプ 'system.int32'であるのに、「ienumerable」というタイプでなければならないのですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。