Garry Pilkington


Application Developer
Liverpool, UK

September 2009 - Posts

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.

Posted: Sep 29 2009, 11:15 AM by capgpilk | with 7 comment(s)
Filed under: , ,
Code Snippet Plugin for Live Writer

For anybody who regularly displays code using Live Writer, then this plugin by Leo Vildosola is a must to check out. When ever I do a rebuild of any of my computers this has to go on and I always have trouble remembering where I found it.

So here are a couple of links.

Leo Vilosola’s blog

Plugin site at codeplex

LINQ Projection

just recently I have been doing quite a bit of work with LINQ and L2S in particular. Although LINQ is nothing new now and I am sure the vast majority of readers out there have had some form of introduction to LINQ. However one of the great things that I still find fascinating is a technique called projection. This is a way to shape data coming back from a query into something more akin to what you want.

   1: class User
   2: {
   3:     public string UserFullName { get; set; }
   4:     public double HoursWorked { get; set; }
   5: }
   6:  
   7: class Program
   8: {
   9:     static void Main()
  10:     {
  11:         List<User> users = new List<User>();
  12:  
  13:         users.Add(new User { HoursWorked = 12.5d, 
  14:             UserFullName = "Ann Admin" });
  15:         users.Add(new User { HoursWorked = 6.5d, 
  16:             UserFullName = "Test User" });
  17:         users.Add(new User { HoursWorked = 8.5d, 
  18:             UserFullName = "Test User" });
  19:         users.Add(new User { HoursWorked = 3.5d, 
  20:             UserFullName = "Test User" });
  21:  
  22:         var q = from user in users
  23:                 where user.UserFullName.Equals("Test User")
  24:                 select new
  25:                  {
  26:                      user.UserFullName,
  27:                      user.HoursWorked,
  28:                      HoursRemaining = (8.5 - user.HoursWorked)
  29:                  };
  30:  
  31:         foreach (var list in q)
  32:         {
  33:             Console.WriteLine(list.UserFullName + " - "
  34:                 + list.HoursWorked
  35:                 + "(" + list.HoursRemaining + ")");
  36:         }
  37:  
  38:         Console.Read();
  39:     }
  40: }

Here the query is creating a new type with three fields. This is especially useful if like above you are doing some form of calculation which you want to use, but is not represented anywhere in the data model.

Posted: Sep 08 2009, 10:00 AM by capgpilk | with 2 comment(s)
Filed under: , ,
More Posts