2014-02-07 49 views
0

我想要的是能夠檢查我的複選框列表中的4個項目,並將它們保存在cookie中。每當用戶重新打開頁面,cookies就會出現。現在我已經擁有了它,它只會選中1個複選框來cookie,如果第一個選擇了它,它會進入它。非常奇怪,我不明白爲什麼所有的cookies都不會保存。所以,這是我的代碼。將多個複選框列表項保存在cookie中

foreach (ListItem item in CheckBoxList1.Items) 
{ 
    if (item.Selected && Request.Cookies["CBL"] != null) 
    { 
     CheckBoxList1.SelectedValue = Request.Cookies["CBL"].Value; 
    } 
} 

然後

protected void Button1_Click(object sender, EventArgs e) 
{ 
    Response.Cookies["CBL"].Value = CheckBoxList1.SelectedValue; 
    Response.Cookies["CBL"].Expires = DateTime.Now.AddDays(30); 
} 

請有人告訴我,我的方式錯誤。

+1

你需要一種將多個值保存到cookie的方法。目前你總是替換cookie中的內容。嘗試pipedelimiting或類似的東西。 – user2453734

回答

2

目前只存儲在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"); 
    } 
} 
+0

chksOne.DataSource =值;給出了一個錯誤。當我刪除它時仍然有效,除非當我更改複選框時,我必須重新打開網頁以查看我的文本框中的值。立即着手解決此問題.. –

+1

您是否在文件中聲明瞭列表值。我只是作爲一個例子,我不知道你的數據源是什麼checkboxlist。 – user2453734

+0

我以爲我有,但我沒有。一切正常。有幾個小問題需要修復,以便將其調整爲我的其他代碼。我看到我沒有正確地做的事情,現在正在用你的作爲參考重寫我的原始代碼。謝謝。 –

2

您應該創建一個模型來存儲選定的值。

public class CheckedItems 
{ 
    public bool c1 {get; set;} 
    public bool c2 {get; set;} 
    ... etc. 
} 

要獲得/從/在你的cookie可以使用這些功能設置any對象:

public bool TryGetValueFromCookie<T>(string cookieName, ref T value) 
{ 
    HttpCookie cookie = null; 
    if (Request.Cookies.AllKeys.Any(key => key.Equals(cookieName))) 
    { 
     cookie = Request.Cookies.Get(cookieName); 
    } 
    if (cookie == null || String.IsNullOrEmpty(cookie.Value)) 
    { 
     return false; 
    } 

    var javaScriptSerializer = new JavaScriptSerializer(); 
    value = javaScriptSerializer.Deserialize<T>(cookie.Value); 
    return true; 
} 

public void SetValueToCookie<T>(string name, T value, DateTime expires) 
{ 
    var javaScriptSerializer = new JavaScriptSerializer(); 
    var cookie = new HttpCookie(name) { Value = javaScriptSerializer.Serialize(value), Expires = expires }; 
    Request.Cookies.Set(cookie); 
} 
相關問題