简体   繁体   English

在Cookie中保存多个复选框列表项

[英]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. 我想要的是能够检查我的复选框列表中的4个项目并将它们保存在Cookie中。 Whenever the user reopens the page the cookies will appear. 每当用户重新打开页面时,cookie就会出现。 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. 就像我现在拥有的那样,它在其中将只选择cookie中的一个复选框,如果第一个被选中,它将转到它。 Very strange and I cannot figure out why all the cookies wont save. 很奇怪,我不知道为什么所有的cookie都不会保存。 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. 您目前仅在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: 要从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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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