程序中保存状态的方式之 Cookies,之前写过一篇关于ViewState的。现在继续总结Cookies方式的
新建的测试页面login
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" %> <!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>
<script type="text/javascript">
function checkSubmit() {
var user = document.getElementById("txtName");
var reg = /^\s*$/;
if (reg.test(user.value)) {
alert("请输入用户名!");
user.focus();
return false;
}
var pwd = document.getElementById("txtPwd");
if (reg.test(pwd.value)) {
alert("请输入密码!");
pwd.focus();
return false;
} return true;
}
</script>
</head>
<body>
<form id="form1" runat="server"> 登录名:<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
密码:<asp:TextBox ID="txtPwd" runat="server"></asp:TextBox>
<asp:Button ID="btn_login" runat="server" Text="登录" onclick="btn_login_Click" OnClientClick="return checkSubmit()"/>
</form>
</body>
</html>
login.aspx
后台.cs文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data; public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
protected void btn_login_Click(object sender, EventArgs e)
{
string name = txtName.Text.Trim();
string pwd = txtPwd.Text.Trim();
if (name == string.Empty)
{ MessageBox.Show(this, "请输入用户名!");
return;
}
if (pwd == string.Empty)
{ MessageBox.Show(this, "请输入密码!");
return;
} if (name == "test" && pwd == "")
{
Response.Cookies.Add(new HttpCookie("comID", ""));
Response.Cookies["comID"].Expires = DateTime.Now.AddDays();//设置过期时间,30天
Response.Redirect("获取cookies.aspx");
}
else {
MessageBox.Show(this,"用户名密码错误!");
} } }
获取cookies.aspx页面后台
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data; public partial class 获取cookies : System.Web.UI.Page
{
public string comid = "";
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Cookies["comID"] != null && Request.Cookies["comID"].Value != "")
{
comid = Request.Cookies["comID"].Value;//获取存入的comid
}
MessageBox.Show(this, "登录id=" + comid);
}
}
删除Cookies
Response.Cookies[CountAdmin].Expires = DateTime.Now.AddDays(-1);//删除cookie
我登录的时候存入了100,访问login.aspx就会跳转到获取cookies页面,提示登录id=100,效果图如下: