如何在ASP.NET MVC中重新填充包含DropDownList的表单?
我相信您在提交并重新显示表单后询问如何维护下拉列表的值.如果是这样,请参阅下面的一个非常简单的示例:
创建一个新的MVC应用程序(使用MVC beta)并将以下内容放在HomeController中:
private DictionarygetListItems() { Dictionary d = new Dictionary (); d.Add("Apple", "APPL"); d.Add("Orange", "ORNG"); d.Add("Banana", "BNA"); return d; } public ActionResult Index() { Dictionary listItems = getListItems(); SelectList selectList = new SelectList(listItems, "Value", "Key"); ViewData["FruitDropDown"] = selectList; return View(); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Index(FormCollection form) { string selectedItem = form["FruitDropDown"]; Dictionary listItems = getListItems(); SelectList selectList = new SelectList(listItems, "Value", "Key", selectedItem); ViewData["FruitDropDown"] = selectList; ViewData["Message"] = "You selected ID:" + selectedItem; return View(); }
并将其放在MainContent标记之间的Home\Index.aspx中:
<%= ViewData["Message"] %><% using (Html.BeginForm()) { %> <%= Html.DropDownList("FruitDropDown","(select a fruit)") %> <% } %>