tags:

views:

916

answers:

2

How do you repopulate a form in ASP.NET MVC that contains a DropDownList?

+5  A: 

I believe you are asking how to maintain the value for a dropdown list after a form is submitted and re-displayed. If so, please see below for a VERY SIMPLE example:

Create a new MVC app (using MVC beta) and place the following in 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();

}

And place this in Home\Index.aspx in between the MainContent tags:

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

<% using (Html.BeginForm()) { %>
<%= Html.DropDownList("FruitDropDown","(select a fruit)") %>
<input type="submit" value="Submit" />
<% } %>
BigJoe714
how would this be different if you used a Model as the input to the Action and not FormCollection? On my end it gives an "Object reference not set to an instance of an object" when View is generated again after validation failed.
NTulip
You're right. I updated the code for MVC 1 (Changed from Beta)
BigJoe714
A: 

I just wanted to add the BigJoe714 has it right except the ...new SelectList(listItems, "Value", "Key", selectedItem) has the key / value switched

The constructor takes these params for this overload

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

The data value should be the key while the data text should be the value.

But otherwise, thanks so much! Another kicka$$ feature of asp.net mvc