次のビューモデルがあります
public class ProjectVM
{
....
[Display(Name = "Category")]
[Required(ErrorMessage = "Please select a category")]
public int CategoryID { get; set; }
public IEnumerable<SelectListItem> CategoryList { get; set; }
....
}
新しいプロジェクトを作成し、 Category
public ActionResult Create()
{
ProjectVM model = new ProjectVM
{
CategoryList = new SelectList(db.Categories, "ID", "Name")
}
return View(model);
}
public ActionResult Create(ProjectVM model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Save and redirect
}
とビューで
@model ProjectVM
....
@using (Html.BeginForm())
{
....
@Html.LabelFor(m => m.CategoryID)
@Html.DropDownListFor(m => m.CategoryID, Model.CategoryList, "-Please select-")
@Html.ValidationMessageFor(m => m.CategoryID)
....
<input type="submit" value="Create" />
}
ビューは正しく表示されますが、フォームを送信すると、次のエラーメッセージが表示されます
InvalidOperationException:キー「CategoryID」を持つViewDataアイテムのタイプは「System.Int32」ですが、タイプは「IEnumerable <SelectListItem>」である必要があります。
@Html.DropDownList()
メソッドを使用して同じエラーが発生し、ViewBag
またはを使用してSelectListを渡した場合ViewData
。