ASP.NET: Recursively Writing all Form Elements to a Cookie

Wednesday, November 12, 2008

There are instances when you need to write all your form elements on a page to a cookie. Here's a simple recursive function, which will write all form values to cookies with the form ids as the cookie keys:

   Private Sub AddToCookie(ByVal Parent)   'Add form values to cookies
For Each c As Control In Parent.Controls
If (TypeOf c Is TextBox) Then
Response.Cookies("Order")(c.ID) = CType(c, TextBox).Text
ElseIf (c.ID = "Product") Then 'Getting value from a DropDownBox
Response.Cookies("Order")(c.ID) = CType(c, DropDownList).SelectedValue
End If
If (c.Controls.Count > 0) Then
AddToCookie(c)
End If
Next
End Sub
This function finds all textboxes and a drop-down box on the page and writes it onto a cookie. This function can also be modified for storing values in session variables.

To retrieve all values of the cookie iteratively, the following code snippet can be used:
       For cookie As Integer = 0 To Request.Cookies("Order").Values.Count - 1
lblOrderInfo.Text += Request.Cookies("Order").Values.Keys.Get(cookie) & " = "
lblOrderInfo.Text += Request.Cookies("Order")(Request.Cookies("Order").Values.Keys.Get(cookie)) & "<br/>"
Next
This code displays all the elements of the cookie as: key = value.

This VB.Net code can be converted to C# by using this converter.