我有Checkbox
在Checked
时放置一个Cookie。当选中Checkbox
时,cookie会存储值“Like”,如果未选中该复选框,则会存储值“Dislike”。但是,选中复选框会存储值“Like”但取消选中它不存储“Dislike”,这是因为当cookie中的值为“Like”时,页面加载应将复选框设置为true
当值为“不喜欢”时,false
。
protected void Page_Load(object sender, EventArgs e)
{
string coursename = Request.QueryString["coursename"].ToString();
HttpCookie recivedCookie = Request.Cookies[User.Identity.Name + coursename + "LikeCookie"];
if (Request.Cookies[User.Identity.Name + coursename + "LikeCookie"] != null)
{
if (recivedCookie.Values["UserLike"] == "Like")
{
LikeCheckBox.Checked = true;
}
else if (recivedCookie.Values["UserLike"] == "Dislike")
{
LikeCheckBox.Checked = false;
}
}
else
{
Response.Write("Cookie is null");
}
}
//===================================================
protected void LikeCheckBox_SelectedIndexChanged(object sender, EventArgs e)
{
string coursename = Request.QueryString["coursename"].ToString();
CheckBox thisCheckBox = sender as CheckBox;
Request.Cookies.Remove(User.Identity.Name + coursename + "LikeCookie"); // To remove the old cookie and create a new cookie whenever the checkbox's index changed
HttpCookie cookie = new HttpCookie(User.Identity.Name + coursename + "LikeCookie");
cookie.Expires.AddDays(10);
if (cookie.Values["UserLike"] == null)
{
if (thisCheckBox.Checked)
{
cookie.Values.Add("UserLike", "Like");
}
else
{
cookie.Values.Add("UserLike", "Dislike");
}
Response.Cookies.Add(cookie);
}
}