Thursday 8 November 2012

cookie example in asp.net:



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

<!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>
 
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        <br />
        <br />
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button"  />  
    </div>
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class cookieexample : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            form_load();

        }
    }
    private void form_load()
    {
        HttpCookie cookie = new HttpCookie("userinfo");
        cookie["country"] = "india";
        cookie["state"] = "andhra";
        cookie["dist"] = "guntur";
        cookie.Expires = DateTime.Now.AddSeconds(5);
        Response.Cookies.Add(cookie);

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        HttpCookie obj = Request.Cookies["userinfo"];
        if (obj != null)
        {
            string country = obj["Country"];
            string state = obj["state"];
            string distr = obj["dist"];
           Label1. Text = "Cookie Found<br/>";
            Label1. Text += "country: " + country;
            Label1. Text += "<br />state: " + state;
            Label1. Text += "<br />district: " + distr;
        }
    }
}

No comments:

Post a Comment