HOME   ARTICLES   DIRECTORY   CONTACT   ABOUT 

Article Menu
superdotnet originals
Intro Lessons
Tips and Tricks
Data Access
Code-Behind/Controls
Quick Code
General ASP.NET
Windows Forms

All Articles
Reader Comments

Resource Options
Alphabetically
Directory

Hosts
.NET Hosts

More Resources
Namespace List
More MSDN Links
QuickStart Lists


Google



Setting and displaying cookies
Article Categories: Data Access | General ASP.NET
Rated: | Number Of Ratings 0 | Add Rating/View Ratings


Below is some quick code to set and display cookies.

<% @Page Language="C#" %>

<script runat="server">


public void Page_Load(Object sender, EventArgs e){

Response.Cookies["FirstName"].Value = "MyName";
Response.Cookies["LastName"].Value = "MyLastName";

}
</script>


First Name: <%=Request.Cookies["FirstName"].Value %><br>
Last Name: <%=Request.Cookies["LastName"].Value %><br>

The HttpCookie and HttpCookieCollection classes allow you to access and edit cookies which have the following properties:

  • Domain - gets or sets the name of the domain to associate the cookie with.
  • Expires - gets or sets expiration date. The value is a standard system date/time.
  • HasKeys - tells whether the cookie has subkeys or not. This property cannot be set.
  • Item - a shortcut to HttpCookieValues[key].
  • Name - gets or sets the name of the cookie.
  • Path - gets or sets the cookie's virtual path.
  • Secure - indicates to transmit the cookie over SSL. Either "true" or "false". Default is true.
  • Value - gets or sets the value of a cookie.
  • Values - assigns multiple values for a cookie.

A cookie's value also needs to be a string. So if you are storing an integer or other datatype you will need to convert it as in:

<% @Page Language="C#" %>

<script runat="server">


public void Page_Load(Object sender, EventArgs e){

int Age = 23;

Response.Cookies["FirstName"].Value = "MyName";
Response.Cookies["LastName"].Value = "MyLastName";
Response.Cookies["Age"].Value = System.Convert.ToString(Age);

}
</script>

First Name: <%=Request.Cookies["FirstName"].Value %><br>
Last Name: <%=Request.Cookies["LastName"].Value %><br>
Age: <%=Request.Cookies["Age"].Value %><br>



Advertisement

Copyright superdotnet.com, all rights reserved. Original articles and site content may not be reproduced from our site without consent from superdotnet.com.
Privacy Policy and User Site Agreement