如何在ASP.NET MVC中重新填充包含DropDownList的表单?

4 asp.net-mvc

如何在ASP.NET MVC中重新填充包含DropDownList的表单?

Big*_*714 5

我相信您在提交并重新显示表单后询问如何维护下拉列表的值.如果是这样,请参阅下面的一个非常简单的示例:

创建一个新的MVC应用程序(使用MVC beta)并将以下内容放在HomeController中:

private Dictionary<string, string> getListItems()
{
    Dictionary<string, string> d = new Dictionary<string, string>();
    d.Add("Apple", "APPL");
    d.Add("Orange", "ORNG");
    d.Add("Banana", "BNA");
    return d;
}

public ActionResult Index()
{
    Dictionary<string, string> 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<string, string> listItems = getListItems();
    SelectList selectList = new SelectList(listItems, "Value", "Key", selectedItem);
    ViewData["FruitDropDown"] = selectList;

    ViewData["Message"] = "You selected ID:" + selectedItem;

    return View();

}
Run Code Online (Sandbox Code Playgroud)

并将其放在MainContent标记之间的Home\Index.aspx中:

<div><strong><%= ViewData["Message"] %></strong></div>

<% using (Html.BeginForm()) { %>
<%= Html.DropDownList("FruitDropDown","(select a fruit)") %>
<input type="submit" value="Submit" />
<% } %>
Run Code Online (Sandbox Code Playgroud)