「postscontroller」でアイテムをビューバッグに入れる必要があることはわかっています
いや、そんなことしなくていいよ。
ビューモデルを定義することから始めることができます:
public class PostViewModel
{
[DisplayName("Select a category")]
[Required]
public string SelectedCategoryId { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
}
コントローラーに入力するもの:
public class PostsController: Controller
{
public ActionResult Index()
{
var model = new PostViewModel();
model.Categories = db.Categories.ToList().Select(c => new SelectListItem
{
Value = c.CategoryId,
Text = c.CategoryName
});
return View(model);
}
}
対応する厳密に型指定されたビュー ( ~/views/posts/index.cshtml
) があります。
@model PostViewModel
@using (Html.BeginForm())
{
@Html.LabelFor(x => x.SelectedCategoryId)
@Html.DropDownListFor(x => x.SelectedCategoryId, Model.Categories, "-- select --")
@Html.ValidationMessageFor(x => x.SelectedCategoryId)
<button type="submit">OK</button>
}