Creating cookie in asp.net

Cookie Example

In this example simply a cookie is used to store a user name, later used to retrieve and display in textbox.  

Create a new web form 

Copy the code below an past in file with .aspx extension

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Cookie_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        &nbsp;<asp:Label ID="Label_result" runat="server"></asp:Label>
    &nbsp;
        <br />
&nbsp;</div>
    <p>
        <asp:Label ID="Label2" runat="server" Text="Name: "></asp:Label>
        <asp:TextBox ID="TextBox_name" runat="server"></asp:TextBox>
        <asp:Button ID="Button_create_cookie" runat="server" 
            onclick="Button_create_cookie_Click" Text="Create Cookie" />
    </p>
    </form>
</body>
</html>


Copy the following code in file with extension .aspx.cs  


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Cookie_Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpCookie cookie = Request.Cookies["Preferences"];
        if (cookie == null)
        {
            Label_result.Text = "<b>Unknown Customer.</b><br /><br />";
         
        }
        else
        {
            Label_result.Text = "<b>Cookie Created.</b><br /><br />";
            Label_result.Text += "welcome: " + cookie["Name"];
        }
    }
    protected void Button_create_cookie_Click(object sender, EventArgs e)
    {
        // Check for a cookie, and only create a new one if
        // one doesn't already exist.
        HttpCookie cookie= Request.Cookies["Preferences"];
        if (cookie == null)
        {
            cookie= new HttpCookie("Preferences");
        }

        cookie["Name"] = TextBox_name.Text;
        cookie.Expires = DateTime.Now.AddYears(1);
        Response.Cookies.Add(cookie);

        Label_result.Text = "<b>Cookie Created.</b><br /><br />";
        Label_result.Text += "New Customer: " + cookie["Name"];
    }
}


No comments:

Post a Comment