您可以使用视图模型:
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>
}