Cookie In ASP.NET | Difference Between Cookie And Session | ASP.NET WebForm
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="CookiesInAsp.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
Username:<asp:TextBox ID="TextBox1" runat="server" Height="26px" Width="184px"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click"/>
</div>
</form>
</body>
</html>
ABOVE FILE IS WebForm1.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CookiesInAsp
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("user");
cookie["username"] = TextBox1.Text;
cookie.Expires = DateTime.Now.AddDays(2);//Cookie data will store in browser upto 2 days(This cookie is called persistent cookie)
Response.Cookies.Add(cookie); //Storing cookie in browser
Response.Redirect("WebForm2.aspx");
}
}
}
ABOVE FILE IS WebForm1.aspx.cs
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="CookiesInAsp.WebForm2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
ABOVE FILE IS WebForm2.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CookiesInAsp
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie cookie = Request.Cookies["user"];
if (cookie != null)
{
Response.Write("Welcome " + cookie["username"].ToString());
}
else
{
Response.Redirect("WebForm1.aspx");
}
}
}
}
ABOVE FILE IS WebForm2.aspx.cs
Comments
Post a Comment