<%@ 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">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>myCookieTest</title>
<style type="text/css">
.divRoot
{
border: dotted 1px red;
padding: 20px;
margin: 20px;
}
.divRoot h1
{
text-align: center;
color: Blue;
background-color:Gray;
}
hr
{
color: Green;
}
</style>
<script type="text/javascript">
function addCookie(key,value) {
var expireDate = new Date(); //cookie 有效日期
expireDate.setMonth(expireDate.getMonth() + 6);
document.cookie = key+"=" + value + "; expires=" + expireDate.toGMTString(); //添加 cookie
alert("添加成功~!!");
return false;
}
function getCookie() {
if (document.cookie != "") {
document.getElementById("spCookie").innerHTML = document.cookie;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="divRoot">
<div>
<h1>
JavaScript -> C#</h1>
<h2>
JavaScript Add Cookie:</h2>
<h3>
Enter The Cookie Value:<input id="nameField" type="text" />
<input id="button1" type="button" value="button" onclick="return addCookie('userName',document.getElementById('nameField').value);" /></h3>
</div>
<hr />
<div>
<h2>
C# Get Cookie:</h2>
<h3>
The Cookie Value:
<asp:Label ID="lblCookie" runat="server"></asp:Label>
<asp:Button ID="btnGetCookie" runat="server" Text="Button" OnClick="btnGetCookie_Click" /></h3>
</div>
</div>
<div class="divRoot">
<div>
<h1>
C# -> JavaScript</h1>
<h2>
C# Add Cookie:</h2>
<h3>
Enter The Cookie Value:
<asp:TextBox ID="txtCookie" runat="server"></asp:TextBox>
<asp:Button ID="btnAddCookie" runat="server" Text="Button" OnClick="btnAddCookie_Click" /></h3>
</div>
<hr />
<div>
<h2>
JavaScript Get Cookie:</h2>
<h3>
The Cookie Value:<span id="spCookie"></span>
<input id="Button2" type="button" value="button" onclick="return getCookie();" /></h3>
</div>
</div>
</form>
</body>
</html>
cookie.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)
{
}
protected void btnGetCookie_Click(object sender, EventArgs e)
{
HttpCookie cookie = Request.Cookies.Get("userName");
if (cookie != null)
{
lblCookie.Text = cookie.Value;
}
else
{
lblCookie.Text = "NULL";
}
}
protected void btnAddCookie_Click(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("SharpCookie");
cookie.Value = txtCookie.Text;
Response.Cookies.Add(cookie);
txtCookie.Text = string.Empty;
}
}