你可以使用一個視圖模型:
public class MyViewModel
{
public string Value { get; set; }
public IEnumerable<SelectListItem> { get; set; }
}
,那麼你可以有一個控制器,它被填充這個模型,並把它傳遞給視圖:
public ActionResult Index()
{
var model = new MyViewModel();
// TODO: you could load the values from your database here
model.Values = new[]
{
new SelectListItem { Value = "Objective", Text = "Objective" },
new SelectListItem { Value = "Subjective", Text = "Subjective" },
};
return View(model);
}
,然後有一個相應的強類型您可以在其中使用Html.DropDownListFor
幫手:
@model MyViewModel
@using (Html.BeginForm())
{
@Html.DropDownListFor(x => x.Value, Model.Values, "Select any value");
<button type="submit">OK</button>
}
最後你會找到d具有到表單將提交一個相應的控制器操作和取視圖模型作爲參數:
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// model.Value will contain the selected value here
...
}