Storing an arbitrary value into a cookie on the client’s machine is something that most site will require at one point or another. It allows for retrieving data across page loads. Below is code snippet of the simple input form in our example.
<form id=”form1″ runat=”server”>
<div>
Cookie Name:
<asp:TextBox ID=”txtCookieName” runat=”server”></asp:TextBox>
<asp:Button ID=”btnSetCookie” runat=”server” Text=”Set Cookie” onclick=”btnSetCookie_Click” />
</div>
</form>
Our next step is to define Button (btnSetCookie) event. Here, we create a HttpCookie. Next, create the cookie’s name and assign the value (as defined in the TextBox txtCookieName). Additionally, we will set the cookie to expire in one minute.
protected void btnSetCookie_Click(object sender, EventArgs e)
{
HttpCookie myCookie = new HttpCookie(”TestCookie”, txtCookieName.Text);
DateTime dtNow = DateTime.Now;
TimeSpan tsMinute = new TimeSpan(0, 0, 1, 0);
myCookie.Expires = dtNow + tsMinute;
}
In this situation, whenever a user clicks the Set button, a cookie (defined as myCookie) will be set that will expire in one minute.
This entry was posted on Tuesday, May 6th, 2008 at 8:35 am and is filed under C#. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
Leave a Reply