ASP.NET MVC 框架默认提供了许多非常有用的帮助器,但似乎总是让人感到困惑的是 Html.DropDownListFor() 帮助器方法。所以在这篇文章中,我将快速回顾一下我用来填充列表的步骤,以及一些启动并运行后更时髦的功能!
在我们的示例中,表单上只有一个下拉列表,显示国家列表,您可以从中选择和提交。
首先,我们需要构建一个视图模型,它将成为确定视图可以显示的数据的契约。
public class IndexViewModel
{
// Stores the selected value from the drop down box.
[Required]
public int CountryID { get; set; }
// Contains the list of countries.
public SelectList Countries { get; set; }
}
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
IndexViewModel viewModel = new IndexViewModel();
viewModel.Countries = new SelectList(GetCountries(), "ID", "Name");
return View(viewModel);
}
[HttpPost]
public ActionResult Index(IndexViewModel viewModel)
{
viewModel.Countries = new SelectList(GetCountries(), "ID", "Name");
if (!ModelState.IsValid)
{ return View(viewModel); }
//TODO: Do something with the selected country...
CMSService.UpdateCurrentLocation(viewModel.CountryID);
return View(viewModel);
}
}
@Html.DropDownListFor(x => x.CountryID, Model.Countries)
@Html.DropDownListFor(x => x.CountryID, Model.Countries, "- please select -")
<link href="@Url.Content("~/Content/themes/base/jquery.ui.all.css")"
type="text/css" rel="stylesheet" />
<script type="text/javascript" src="@Url.Content("></script>
<script type="text/javascript" src="@Url.Content("></script>
<link type="text/css" rel="stylesheet" href="@Url.Content("~/Content/selectmenu.css")" />
<script src="@Url.Content("~/Scripts/selectmenu.js")" type="text/javascript"></script>
<script type="text/javascript">
$('select').selectmenu();
</script>