Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript and ASP.NET - Cookies with Key / Value Pairs

This question mixes client-side scripting with server-side parsing.

In some cases, I'm writing a cookie to the user's browser using the document.cookie property. In other cases, I'm writing the same cookie to the user's browser through the ASP.NET Response object.

When I'm writing the HttpCookie on the server-side, I am using the Values collection (http://msdn.microsoft.com/en-US/library/system.web.httpcookie.values%28v=VS.80%29.aspx) to store key/value pairs in the cookie. I would also like to be able to write key-value pairs to the cookie through JavaScript.

How do I create cookies with Key/Value pairs via JavaScript that ASP.NET can parse?

Thank you!

like image 473
user208662 Avatar asked Nov 05 '22 14:11

user208662


2 Answers

Are you able to get the value of the main cookie via javascript.

For example if your main cookie name is UserDetails and the sub elements are FirstName and LastName asp.net should set the UserDetails Cookie value as follows.

FirstName=Jon&LastName=Doe

Thanks,

like image 71
Michael Grassman Avatar answered Nov 15 '22 06:11

Michael Grassman


I recently wrote a blog post about this exact topic. Here's the JavaScript to create an ASP.NET HttpCookie-compatible multi-valued cookie:

var setMultiValuedCookie = function(name, values) {
    var valuePairs = [];
    for (var n in values) {
        valuePairs.push(n + "=" + values[n]);
    }
    var cookieValue = valuePairs.join("&");
    document.cookie = name + "=" + cookieValue;
};

// Usage:
setMultiValuedCookie("TestCookie", { firstName: "John", lastName: "Doe" });
like image 23
cdmckay Avatar answered Nov 15 '22 06:11

cdmckay