DropDownListFor ヘルパーは最初の引数として渡されたラムダ式を使用し、特定のプロパティの値を使用するため、コンストラクターの最後の引数SelectList
(選択した値 ID を渡すことができるようにする必要がある) は無視されます。
したがって、これを行う醜い方法は次のとおりです。
モデル:
public class MyModel
{
public int StatusID { get; set; }
}
コントローラ:
public class HomeController : Controller
{
public ActionResult Index()
{
// TODO: obviously this comes from your DB,
// but I hate showing code on SO that people are
// not able to compile and play with because it has
// gazzilion of external dependencies
var statuses = new SelectList(
new[]
{
new { ID = 1, Name = "status 1" },
new { ID = 2, Name = "status 2" },
new { ID = 3, Name = "status 3" },
new { ID = 4, Name = "status 4" },
},
"ID",
"Name"
);
ViewBag.Statuses = statuses;
var model = new MyModel();
model.StatusID = 3; // preselect the element with ID=3 in the list
return View(model);
}
}
意見:
@model MyModel
...
@Html.DropDownListFor(model => model.StatusID, (SelectList)ViewBag.Statuses)
リアルビューモデルを使用した正しい方法は次のとおりです。
モデル
public class MyModel
{
public int StatusID { get; set; }
public IEnumerable<SelectListItem> Statuses { get; set; }
}
コントローラ:
public class HomeController : Controller
{
public ActionResult Index()
{
// TODO: obviously this comes from your DB,
// but I hate showing code on SO that people are
// not able to compile and play with because it has
// gazzilion of external dependencies
var statuses = new SelectList(
new[]
{
new { ID = 1, Name = "status 1" },
new { ID = 2, Name = "status 2" },
new { ID = 3, Name = "status 3" },
new { ID = 4, Name = "status 4" },
},
"ID",
"Name"
);
var model = new MyModel();
model.Statuses = statuses;
model.StatusID = 3; // preselect the element with ID=3 in the list
return View(model);
}
}
意見:
@model MyModel
...
@Html.DropDownListFor(model => model.StatusID, Model.Statuses)