014. asp.net实现记住密码的功能
1 protected void Button1_Click(object sender, EventArgs e) 2 { 3 if (txtname.Text.Trim().Equals("mr") && txtpwd.Text.Trim().Equals("mrsoft")) 4 { 5 Session["username"] = txtname.Text.Trim(); 6 if (ckbauto.Checked) 7 { 8 if (Request.Cookies["username"] == null) 9 { 10 Response.Cookies["username"].Expires = DateTime.Now.AddDays(30); 11 Response.Cookies["userpwd"].Expires = DateTime.Now.AddDays(30); 12 Response.Cookies["username"].Value = txtname.Text.Trim(); 13 Response.Cookies["userpwd"].Value = txtpwd.Text.Trim(); 14 } 15 } 16 Response.Redirect("admin.aspx"); 17 } 18 else 19 { 20 ClientScript.RegisterStartupScript(this.GetType(),"","alert('用户名或密码错误!');",true); 21 } 22 } 23 protected void txtname_TextChanged(object sender, EventArgs e) 24 { 25 if (Request.Cookies["username"] != null) 26 { 27 if (Request.Cookies["username"].Value.Equals(txtname.Text.Trim())) 28 { 29 txtpwd.Attributes["value"] = Request.Cookies["userpwd"].Value; 30 } 31 } 32 }
注: 对于txtname控件, 需要将其的AutoPostBack属性, 设置为True, 这样当用户输入用户名之后, 会自动回发到服务器, 执行TextChanged事件