在cookie中保存多个checkboxlist项

时间:2014-02-07 18:37:56

标签: c# asp.net

我想要的是能够检查我的复选框列表中的4个项目并将它们保存在cookie中。每当用户重新打开页面时,cookie都会出现。正如我现在所拥有的那样,它只会选择1个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);
}

请有人告诉我我的方式错误。

2 个答案:

答案 0 :(得分:2)

您应该创建一个模型来存储选定的值。

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

要从/中获取/设置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);
}

答案 1 :(得分: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");
    }
}