目前只存儲在cookie中的一個值。您需要存儲所有選定的值,然後檢索所有值。你可以嘗試下面的東西。管劃定值:
//chksOne is checkboxlist in the markup.
//CUSTOM DATASOURCE FOR CHECKBOXLIST REPLACE WITH YOUR DATASOURCE
public List<string> Values = new List<string>() { "CHK 1", "CHK 2", "CHK 3", "CHK 4" };
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
return;
chksOne.DataSource = Values;
chksOne.DataBind();
if (Request.Cookies.AllKeys.Contains("CBL"))
{
string value = Request.Cookies["CBL"].Value;
if (value == null)
return;
string[] vals = value.Split('|');
for (int i = 0, ii = chksOne.Items.Count; i < ii; i++)
if (vals.Contains(chksOne.Items[i].Value))
chksOne.Items[i].Selected = true;
}
}
protected void chksOne_SelectedIndexChanged(object sender, EventArgs e)
{
CheckBoxList list = sender as CheckBoxList;
if(list == null)
return;
List<string> tmpValues = new List<string>();
for (int i = 0, ii = list.Items.Count; i < ii; i++)
{
if (list.Items[i].Selected)
tmpValues.Add(list.Items[i].Value);
}
Response.Cookies.Add(new HttpCookie("CBL", string.Join("|", tmpValues.ToArray())));
Response.Cookies["CBL"].Expires = DateTime.Now.AddDays(30);
}
爲了使這種可重複使用的,你可以創建一對夫婦的擴展方法:
public static class Extensions
{
public static string GetValues(this CheckBoxList list)
{
List<string> tmpValues = new List<string>();
for (int i = 0, ii = list.Items.Count; i < ii; i++)
{
if (list.Items[i].Selected)
tmpValues.Add(list.Items[i].Value);
}
return string.Join("|", tmpValues.ToArray());
}
public static void SaveValuesToCookie(this CheckBoxList list, string cookieName)
{
string values = list.GetValues();
HttpContext.Current.Response.Cookies.Add(new HttpCookie(cookieName, values));
HttpContext.Current.Response.Cookies[cookieName].Expires = DateTime.Now.AddDays(30);
}
public static void CheckItemsFromCookie(this CheckBoxList list, string cookieName)
{
//MAKE SURE THE COOKIE EXISTS, IF NOT, THERE IS NOTHING WE CAN DO
if (!HttpContext.Current.Request.Cookies.AllKeys.Contains(cookieName))
return;
//MAKE SURE THE COOKIE HAS VALUE AND IT IS NOT NULL
string value = HttpContext.Current.Request.Cookies[cookieName].Value;
if (value == null)
return;
string[] vals = value.Split('|');
for (int i = 0, ii = list.Items.Count; i < ii; i++)
if (vals.Contains(list.Items[i].Value))
list.Items[i].Selected = true;
}
}
那麼如何使用代碼將是:
public partial class Default : System.Web.UI.Page
{
public List<string> Values = new List<string>() { "CHK 1", "CHK 2", "CHK 3", "CHK 4" };
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
return;
chksOne.DataSource = Values;
chksOne.DataBind();
//EXTENSION METHOD DEFINED ABOVE
chksOne.CheckItemsFromCookie("CBL");
}
protected void chksOne_SelectedIndexChanged(object sender, EventArgs e)
{
CheckBoxList list = sender as CheckBoxList;
if(list == null)
return;
//EXTENSION METHOD DECLARED IN CLASS EXTENSIONS ABOVE
list.SaveValuesToCookie("CBL");
}
}
你需要一種將多個值保存到cookie的方法。目前你總是替換cookie中的內容。嘗試pipedelimiting或類似的東西。 – user2453734