CookieSetValue.aspx
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Net" %>
<!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) {
if (!this.IsPostBack) {
HttpCookie testCokkie = new HttpCookie("ExampleCookie");
testCokkie.Expires = DateTime.Now.AddDays(5);
Response.Cookies.Add(testCokkie);
}
}
protected void Button1_Click(object sender, System.EventArgs e) {
HttpCookie ExampleCookie = Request.Cookies["ExampleCookie"];
ExampleCookie["Name"] = TextBox1.Text.ToString();
ExampleCookie["City"] = TextBox2.Text.ToString();
Response.Cookies.Add(ExampleCookie);
}
protected void Button2_Click(object sender, System.EventArgs e) {
HttpCookie exampleCookie = Request.Cookies["ExampleCookie"];
if (exampleCookie != null) {
string name = exampleCookie["Name"];
string city = exampleCookie["City"];
label1.Text = "Cookie found and read<br />";
label1.Text += "Name: " + name + "<br />City: " + city;
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>asp.net cookie example: how to set value in a cookie</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Red">asp.net cookie example: set value</h2>
<asp:Label
ID="label1"
runat="server"
Font-Size="Large"
ForeColor="SeaGreen"
Font-Italic="true"
>
</asp:Label>
<br /><br />
<asp:Label ID="Label2" runat="server" Text="Name">
</asp:Label>
<asp:TextBox ID="TextBox1" runat="server" BackColor="LightGreen">
</asp:TextBox>
<br />
<asp:Label ID="Label3" runat="server" Text="City">
</asp:Label>
<asp:TextBox ID="TextBox2" runat="server" BackColor="LightGreen">
</asp:TextBox>
<br />
<asp:Button
ID="Button1"
runat="server"
Text="Set cookie value"
OnClick="Button1_Click"
Font-Bold="true"
ForeColor="Crimson"
/>
<asp:Button
ID="Button2"
runat="server"
Text="Read cookie"
OnClick="Button2_Click"
Font-Bold="true"
ForeColor="DarkGreen"
/>
</div>
</form>
</body>
</html>
No comments:
Post a Comment