User Preferences Sample

      

This sample uses cookies to save user preferences. A small form allows you to select colors for the foreground and background. The values are saved in cookies and read back when the form reloads.

Behind the Scenes

This sample uses one file, Prefer.asp, which creates an HTML form that posts information back to the same ASP page.

When creating a page to save settings to cookies, you will not generally use this method. Instead, you would typically use one page to store settings, and use other pages in your application to read them back.

First, this ASP page checks whether the HTML form has posted back to the ASP page already. If it has, two cookies are written using server-side Visual Basic®, Scripting Edition (VBScript).

If Len(Request("BGColor")) > 0 then
   Response.Cookies("BGColor") = Request("BGColor")
   Response.Cookies("FGColor") = Request("FGColor")
End If

Then, the code checks to see if a cookie called BGColor has been written out. If there is no cookie, the page has not saved any preferences and the index of the drop-down boxes should be set to 0. If the cookies exist, they are read into variables to be placed into client-side JavaScript.

If Request.Cookies("intBGColor") = "" then
   intBG = 0
   intFG = 0
Else
   intBG = Request.Cookies("intBGColor")
   intFG = Request.Cookies("intFGColor")
End If

The BODY tag is used to set the background color and to call a function to set the index values of the drop-down boxes.

<BODY BGCOLOR=<%= Request.Cookies("BGColor")%> ONLOAD="setcolor()">

The SetColor function uses JavaScript to set the index values. The code gets the values from cookies that were read using server-side VBScript.

   function setcolor() {
      document.Pref.BGColor.selectedIndex = <%=intBG%>;
      document.Pref.FGColor.selectedIndex = <%=intFG%>;
   }

The foreground color is set using the FONT tag.

<FONT COLOR=<%=Request.Cookies("FGColor")%>>

The rest of the page creates a form that, when submitted, will call a function to write the index values of the drop-down boxes into cookies and post the information back to this same ASP.