Lesson 9 | Response.Cookies |
Objective | Store user-specific information on the client computer. |
ASP - User-Specific Information
In an earlier lesson, we covered retrieving previously set cookie values. Those cookie values needed to be set earlier on the process, and that's the focus of this lesson. Since you are creating cookies with the Response object, you have more options than when you are receiving them with the Request object.
When you use the Cookie collection of the Response object, the rules are simple. If the specified cookie does not already exist, it is created. If there is a cookie with the same name, the cookie takes the new value set by your script. The syntax for setting cookies is:
Response.Cookies(cookiename)[(key)|.attribute] = value
The key lets you create cookies with keys (nested cookies), as we did for setting user preferences in a previous example:
.
.
<TABLE>
<TR>
<TD>Size</TD>
<TD>
<%= Request.Cookies("Preferences")("Size")%>
</TD>
</TR>
<TR>
<TD>Neck style</TD>
<TD>
<%= Request.Cookies("Preferences")("Neck")%>
</TD>
</TR>
</TABLE>
You can also specify an attribute, such as an expiration date, for each cookie or key value.
Creating and updating cookies
Creating or updating the cookies we retrieved could be done directly with this code segment:
.
.
<%= Response.Cookies("Preferences")("Size") = "XXL"%>
<%= Response.Cookies("Preferences")("Neck") = "17.5"%>
.
.
We could also have set the values in the cookies by using data from a submitted HTML FORM
in this way:
.
.
<%= Response.Cookies("Preferences")("Size") = Request.Form("Size")%>
<%= Response.Cookies("Preferences")("Neck") = Request.Form("Neck")%>
.
.
Creating Cookies with and without Keys
In some situations, you may need to create multiple cookies, some with single values and some with keys (nested values).
Here is a code segment, again using submitted HTML FORM
data, that shows the difference in syntax between the two:
<% Response.Cookies("Name") = Request.Form("Name")%>
<% Response.Cookies("Preferences")("Size") = Request.Form("Size") %>
For the first cookie, there are no keys, so just the cookie is given: Name
.
In the second line, the Preferences cookie has several keys, including Size.
The next lesson describes how to direct the user to a different Web page.