界面
点击登录按钮的代码
protected void btnLogin_Click(object sender, EventArgs e)
{
if (remember_long.Checked)
{
HttpCookie cookie = new HttpCookie("USER_COOKIE");
cookie.Values.Add("UserName", this.username.Value.Trim());
cookie.Expires = System.DateTime.Now.AddDays(7.0);
HttpContext.Current.Response.Cookies.Add(cookie);
}
else if (remember_long.Checked==false)
{
Response.Cookies["USER_COOKIE"].Expires = DateTime.Now;
}
Response.Redirect("ok.aspx");
}
load事件里代码,提交表单
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//读取保存的Cookie信息
HttpCookie cookies = Request.Cookies["USER_COOKIE"];
if (cookies != null)
{
//如果Cookie不为空,则将Cookie里面的用户名和密码读取出来赋值给前台的文本框。
this.username.Value = cookies["UserName"];
this.remember_long.Checked = true;
}
}
}
如果是密码框,使用上面的方法不能给密码框赋值,需要注意两点
1、密码框使用服务器端控件
2、赋值代码区别:this.password.Attributes["value"]= cookies["Pwd"];
不是this.password.Value = cookies["Pwd"];