简体   繁体   中英

Saving multiple checkboxlist items in a cookie

What I want is to be able to check the 4 items I have in my checkboxlist and save them in a cookie. Whenever the user reopens the page the cookies will appear. As I have it now I have it where it will only select 1 of the checkboxes to cookie and if the first one is selected first it goes to it. Very strange and I cannot figure out why all the cookies wont save. So, here is my code for it.

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

and then

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

Please someone tell me the error of my ways.

You are currently only storing one value in the cookie. You need to store all the values that are selected and then retrieve all the values. You can try something like below. Pipe delimit the values:

//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);
}

To make this re-usable you can create a couple of extension methods:

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;
    }
}

Then the how to use code would be:

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");
    }
}

You should create a model to store selected values.

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

To get/set any object from/in cookie you can use these functions:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM