29 September 2009
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.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.Displaying the DropDownList in a viewThis 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.