When Chapter 3 looked at the Request object, you saw how cookies can be accessed on the server when a request is received from the browser. Cookies store information on the client machine, and are sent to the server with each request for information. The server can set or change the cookie's values, and the Response object provides an interface for just this purpose. Like the Request object, it holds a cookies collection ”but this time you can use it to write values to the cookies that are sent back with your page.
The following code adds a cookie named Name with the value of Rick. It gets the HttpCookieCollection by calling Response.Cookies . It creates an HttpCookie object named "Name" and sets its value to "Rick" . Finally, the newly-created cookie is added to the collection.
Dim objCookies as HttpCookieCollection objCookies = Response.Cookies Dim objHttpCookie as new HttpCookie( "Name" ) objHttpCookie.Value = "Rick" objCookies.Add( objHttpCookie )
A page on www.UsingASP.net enables you to add your own cookie, with a value that you specify. The following code provides a form into which users can name their cookies and specify values:
<form method="POST" action="CookiesResult.aspx"> Enter a Cookie Name:<br> <input type="text" name="Name" size="20"><br> Enter a Value: <br> <input type="text" name="Value" size="20"><br> <input type="submit" value="Submit" name="B1"> <input type="reset" value="Reset" name="B2"> </form>
This code is part of the page that you can find at www.UsingASP.net. Select Chapter Examples, Chapter 4, then Cookies. You can see the rendered page in Figure 4.6.
Figure 4.6. You must enter a cookie name and value.
After the form has been submitted to CookiesResult.aspx, the cookie collection is retrieved, a new cookie is created and set, and the new cookie is added. Following this, the cookie collection is enumerated and shown in the HTML document. Your new cookie shows up in the list.
<% Dim objCookies as HttpCookieCollection objCookies = Response.Cookies Dim strName as String strName = Request.Form( "Name" ) Dim objHttpCookie as new HttpCookie( strName ) objHttpCookie.Value = Request.Form( "Value" ) objCookies.Add( objHttpCookie ) objCookies = Request.Cookies Dim Item As String For Each Item in objCookies %> Cookie name <font color="red">'<%=Item%>'</font> Cookie value <font color="blue">'<%=objCookies(Item).Value%>'</font> <% Next %>
This code is part of the page that is invoked by filling out the form shown in Figure 4.6 and clicking the Submit button. You can see the rendered page in Figure 4.7.
Figure 4.7. The cookies are enumerated in the window.