Cookies with multiple values in asp .net

In this asp .net tutorial we will learn how to write,read and delete cookies with multiple values. Multiple values are stored in the form of name-value pairs in a single cookie. Cookies with more than one value are very useful to store related information into single cookie rather than creating and maintaining multiple cookies. E.g. You can store Name and age of user in a single cookie rather than creating separate cookie for name and for age. 
 
To learn about how to Write single value cookies, Read single value cookie and Delete cookie follow this article:
 
 
Some of the advantages of using Multiple value cookies over single value cookies:
1) You can put similar information into a single cookie.
2) Using Multiple valued cookies also limits the number of cookie files supported by browser.
3) You can apply expiration to the cookie collection.
 
Create Cookie with multiple values:
 
        //---- Method first
        Response.Cookies["NameOfCookie"]["Name"] = "CodingFusion";
        Response.Cookies["NameOfCookie"]["Age"] = "5";
        Response.Cookies["NameOfCookie"].Expires = DateTime.Now.AddDays(1);

        //---- Method second
        //--- Create Cookie Object.
        HttpCookie cookieObject = new HttpCookie("NameOfCookie");

        //--- Add values to cookie in Key,Value format.
        cookieObject["Name"] = "CodingFusion";
        cookieObject["Age"] = "5";

        //---- Set expiry time of cookie.
        cookieObject.Expires.AddDays(5);

        //---- Add cookie to cookie collection.
        Response.Cookies.Add(cookieObject);
 
Read Cookie with multiple values:
 
        //--- Get cookie Collection.
        HttpCookie cookieObj = Request.Cookies["NameOfCookie"];

        //--- Check for null 
        if (cookieObj != null)
        {
            //--- To read values from cookie collection we will use Keys used while creating cookie.
            string name = cookieObj["Name"];
            string age = cookieObj["Age"];

            string result = "Your Name is " + name + " and your age is " + age;
        }
 
 
Delete cookie with multiple value: 
 
        //--- Get cookie Collection.
        HttpCookie cookieObj = Request.Cookies["NameOfCookie"];

        //--- To delete cookie we will add negative time.
        cookieObj.Expires = DateTime.Now.AddDays(-1);

        //---- Add cookie to cookie collection.
        Response.Cookies.Add(cookieObj);
 
Tip: Sometimes cookies are disabled by users in browser in that case you can also check whether a Browser Accepts Cookies.
 
 
cookies-multiple-values-example-in-asp-net-codingfusion
About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice