功能說明:
1.畫面上放一個TextBox、CheckBox、Button
2.第一次登入時若勾選CheckBox且TextBox的值正確,將TextBox的值寫入Cookie
3.登入時檢查Cookie使否有值,若有、自動將Cookie值複製到TextBox,且將CheckBox打勾
4.登入時若將CheckBox勾選取消、會連同Cookie資料清除
5.按下Button後檢查Textbox是否正確,若正確、Button.Text="OKOK"
6.若TextBox值不正確、Cookie資料清除
程式範例:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
//取cookie資料
if (Request.Cookies["txt1"] != null)
{
CheckBox1.Checked = true;
TextBox2.Text = (Request.Cookies["txt1"].Value.ToString());
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//狀況1:若已勾記住帳號,重新寫入cookie
if (CheckBox1.Checked)
{
if (TextBox2.Text == "aa")
{
Button1.Text = "OKOK!";
//將正確資料寫入cookie
HttpCookie cookie = new HttpCookie("txt1");
cookie.Value = TextBox2.Text;
cookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(cookie);
}
}
//狀況2:取消勾選cookie且cookie若有資料須清空
//因為不能直接刪除cookie,只要讓cookie過期變成失效,系統會自行刪除cookie
if(!CheckBox1.Checked)
{
if (Request.Cookies["txt1"] != null)
{
HttpCookie cookie = new HttpCookie("txt1");
cookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(cookie);
}
if (TextBox2.Text == "aa")
Button1.Text = "OKOK!";
}
}
沒有留言:
張貼留言