TempData and DropDownList in ASP.Net MVC
TempData
Sometimes while developing web applications, you have
a need to keep certain data between web requests. In asp.Net
MVC you can use TempData which will keep hold of any values
you pass to it for that request and the next request when it
is then removed. This is a great way of keeping form
elements at a particular state during form submission from
an mvc view. In the following example I will briefly explain
how to render a drop down list populated with data which
will keep the selected value across form submission.
The ActionResult
In the ActionResult in the controller for the view you
get the value of the drop down selected item which is held
in the FormCollection. Then simply call a method that
returns a IList<SelectListItem> collection, passing in
the selected item. The resulting collection is then passed
to a TempDataDictionary which is in turn passed back to the
view.
1: public ActionResult DistrictsView(FormCollection collection)
2: {
3: int selectedValue = Convert.ToInt32(collection["Districts"]);
4:
5: TempData["Districts"] = DropDownPopulators.GetDistricts(selectedValue);
6:
7: return View();
8:
9: }
Keeping the selected value
The drop down list takes a collection of SelectlistItems in
the form of text/value pairs. What the following method does
is generate a dictionary collection of districts and the
associated key, then creates the IList<SelectListItem>
for the drop down, but it also sets the selected property to
true for the selected value passed in from the view. The
GetDistrictList method call simply returns a dictionary
collection from the database of district and integer values.
1: public static IList<SelectListItem> GetDistricts(int selectedValue)
2: {
3: IList<SelectListItem> districts = new List<SelectListItem>();
4: Dictionary<int, string> districtCollection
5: = DataRepository.GetDistrictList();
6:
7: SelectListItem itemAll = new SelectListItem();
8:
9: itemAll.Value = "0";
10: itemAll.Text = "All";
11: districts.Add(itemAll);
12:
13: foreach (var dist in districtCollection)
14: {
15: if (dist.Key == selectedValue)
16: {
17: SelectListItem item = new SelectListItem();
18:
19: item.Value = dist.Key.ToString();
20:
21: item.Text = dist.Value;
22: item.Selected = true;
23: districts.Add(item);
24: }
25: else
26: {
27: SelectListItem item = new SelectListItem();
28:
29: item.Value = dist.Key.ToString();
30:
31: item.Text = dist.Value;
32: item.Selected = false;
33: districts.Add(item);
34: }
35: }
36: return districts;
37: }
Displaying the DropDownList in a view
1: <%=Html.DropDownList("Districts", TempData["Districts"]
2: as List<SelectListItem>
3: , new { @onchange = "this.form.submit();" })%>
This binds the Districts TempData to the DropDownList helper in the view. The clever bit here is the creation of the form submit java script when the drop down is changed.