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>
|