How to store multiple values into Single cookie as Key value pair

Here I will code you how to store and retrieve the multiple values in cookies in asp.net. In cookies we are storing data as a Key value pair. Initially data will be stored in dictionary object as key value pair, later it will be stored as Cookies. While retrieving initially cookie values will be assigning to NameValueCollection and from there we can split the data we need. You need to go through Dictionary Object in C# and  How to create and retrieve data using Cookies before understanding this tutorial.



Additional Name space :

using System.Collections.Specialized;

ASPX :

<div>
<asp:Button ID="Button1" runat="server" Text="Set cookie"
            onclick="Button1_Click" />
<br />
<br />
<asp:Button ID="Button2" runat="server" onclick="Button2_Click"
            Text="Get Cookie" />
</div>

C#

protected void Button1_Click(object sender, EventArgs e)
 {
    Dictionary<string, string> Dic = new Dictionary<string, string>();
    Dic.Add("wp", "Windows Mobile");
    Dic.Add("an", "Android");
    Dic.Add("ip", "Iphone");
    Dic.Add("sf", "snail fish");
    SetMultipleCookies("Mob_Cook", Dic);
    Response.Write("<script>alert('Details saved into Cookies');</script>");
  }


protected void Button2_Click(object sender, EventArgs e)
 {
   Dictionary<string, string> Dic_get_Cook = new Dictionary<string, string>();
    Dic_get_Cook = GetMultipleCookies("Mob_Cook");
     if (Dic_get_Cook.Count > 0)
       {
         foreach (var pair in Dic_get_Cook)
          {
            Response.Write(pair.Value + "<br>");
          }
       }
       else
        {
          Response.Write("<script>alert('No Cookies here');</script>");
        }
  }


public void SetMultipleCookies(string cookieName, Dictionary<string, string> dic)
  {
    HttpCookie hc = new HttpCookie(cookieName);
    foreach (KeyValuePair<string, string> val in dic)
     {
       hc[val.Key] = val.Value;
      }
     hc.Expires = DateTime.Now.Add(TimeSpan.FromHours(20000));
     GetHttpResponse().Cookies.Add(hc);
  }


public Dictionary<string, string> GetMultipleCookies(string cookieName)  
 {
   Dictionary<string, string> dicVal = new Dictionary<string, string>();
   if (GetHttpRequest().Cookies[cookieName] != null)            
    {
     HttpCookie cok = GetHttpRequest().Cookies[cookieName];      
         if (cok != null)
          {
           NameValueCollection nameValueCollection = cok.Values;   
            foreach (string key in nameValueCollection.AllKeys)     
             {
                        dicVal.Add(key, cok[key]);
             }
          }
     }
    return dicVal;
  }
   

  public static HttpRequest GetHttpRequest() 
  {
    return HttpContext.Current.Request;
  }

  public static HttpResponse GetHttpResponse()
  {
    return HttpContext.Current.Response;
  }