Pages

Tuesday 23 April 2013

Write a program in C# for managing cookies in ASP.NET.

Write a program in C# for managing cookies in ASP.NET.

Program:

.aspx file


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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">  
    protected void Page_Load(object sender, System.EventArgs e) {  
        HttpCookie userCookie = new HttpCookie("UserInfo");  
        userCookie["Country"] = "India";  
        userCookie["City"] = "Surat";  
        userCookie["Name"] = "Sizar";  
        userCookie.Expires = DateTime.Now.AddDays(3);  
        Response.Cookies.Add(userCookie);  
        Label1.Text = "Cookie create successful!<br><br/>";  
          
        HttpCookie cookie = Request.Cookies["UserInfo"];  
          
        if (cookie != null)   
        {  
            string country = cookie["Country"];  
            string city = cookie["City"];  
            string name = cookie["Name"];  
            Label2.Text = "Cookie Found and read<br/>";  
            Label2.Text += "Name: " + name;  
            Label2.Text += "<br />Country: " + country;  
            Label2.Text += "<br />City: " + city;  
        }  
    }  
</script>  
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <div>  
       <asp:Label ID="Label1" runat="server" Font-Size="Large" ForeColor="green" ></asp:Label>  
        <asp:Label ID="Label2" runat="server" Font-Size="Large" ForeColor="red"></asp:Label>  
    </div>  
    </div>
    </form>
</body>
</html>

.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 : System.Web.UI.Page


{


protected void Page_Load(object sender, EventArgs e)
{

}

}




Demo:

Write a program in C# for managing cookies in ASP.NET.
Write a program in C# for managing cookies in ASP.NET.

No comments:

Post a Comment