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

时间:2008-11-17 22:42:55

标签: asp.net-mvc

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

2 个答案:

答案 0 :(得分: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();

}

将它放在MainContent标签之间的Home \ Index.aspx中:

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

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

答案 1 :(得分:0)

我只想添加BigJoe714,除了...新的SelectList(listItems,“Value”,“Key”,selectedItem)具有键/值切换

构造函数将这些参数用于此重载

public SelectList( IEnumerable items, string dataValueField, string dataTextField, object selectedValue );

数据值应该是键,而数据文本应该是值。

但除此之外,非常感谢! asp.net mvc的另一个kicka $$功能