I'm using JQuery.Cookie to store a javascript object as a cookie value:
var refinerData = {};
// Read in the current cookie if it exists:
if ($.cookie('RefinerData') != null) {
refinerData = JSON.parse($.cookie('RefinerData'));
}
// Set new values based on the category and filter passed in
switch(category)
{
case "topic":
refinerData.Topic = filterVal;
break;
case "class":
refinerData.ClassName = filterVal;
break;
case "loc":
refinerData.Location = filterVal;
break;
}
// Save the cookie:
$.cookie('RefinerData', JSON.stringify(refinerData), { expires: 1, path: '/' });
When I debug in firebug, the value of the cookie value seems to be formatted correctly:
{"Topic":"Disease Prevention and Management","Location":"Hatchery Hill Clinic","ClassName":"I have Diabetes, What can I Eat?"}
I'm writing a SharePoint web part in C# that reads the cookie in and parses it:
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies["RefinerData"];
if (cookie != null)
{
string val = cookie.Value;
// Deserialize JSON cookie:
JavaScriptSerializer serializer = new JavaScriptSerializer();
var refiners = serializer.Deserialize<Refiners>(cookie.Value);
output.AppendLine("Deserialized Topic = " + refiners.Topic);
output.AppendLine("Cookie exists: " + val);
}
}
I have a Refiners class for serializing to:
public class Refiners
{
public string Topic { get; set; }
public string ClassName { get; set; }
public string Location { get; set; }
}
However, this code throws an "Invalid JSON Primitive" error. I can't figure out why this isn't working. One possibility is that its not reading the cookie correctly. When I print out the value of the cookie as a string, I get:
%7B%22Topic%22%3A%22Disease%20Prevention%20and%20Management%22%2C%22Class%22%3A%22Childbirth%20%26%20Parenting%202013%22%2C%22Location%22%3A%22GHC%20East%20Clinic%22%7D