你可以使用一個視圖模型:
public class MyViewModel
{
[DisplayName("Company")]
public int CompanyId { get; set; }
public IEnumerable<SelectListItem> Companies { get; set; }
}
,然後讓你的控制器動作實例化,填充和通過這個視圖模型到視圖:
public class CompaniesController: Controller
{
public ActionResult Index()
{
List<Company> companies = getCompanies();
var model = new MyViewModel();
model.Companies = companies.Select(x => new SelectListItem
{
Value = x.companyID.ToString(),
Text = x.companyName
});
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// model.CompanyId will contain the selected value here
return Content(
string.Format("You have selected company id: {0}", model.CompanyId)
);
}
}
最後一個強類型的視圖您可以呈現包含下拉列表的HTML表單:
@model MyViewModel
@using (Html.BeginForm())
{
@Html.LabelFor(x => x.CompanyId)
@Html.DropDownListFor(x => x.CompanyId, Model.Companies)
<button type="submit">OK</button>
}
http://stackoverflow.com/questions/7247871/bind ing-to-a-dropdownlist-in-mvc3?rq = 1 – 2012-08-05 16:27:05