Reputation: 3954
I have a view in ASP.NET MVC3 that makes a call to an AsyncController to get a partial view. I also want to set some data as a JSON string to a cookie that I can read from the jQuery.
Here is my View:
$.ajax({
type: "POST",
url: '/ProductAsync/GetProductData',
data: JSON.stringify({
Product: thisProduct
}),
contentType: "application/json; charset=utf-8",
success: function (returndata) {
$('div#' + thisProduct).empty().html(returndata);
var productDataJson = $.cookie(thisProduct + "-ProductData");
alert(productDataJson);
}
});
Here is my AsyncControlleraction:
public class ProductAsyncController : AsyncController
{
[HttpPost]
public ActionResult GetProductData(string Product)
{
ProductData model = ProductModel.GetProductData(Product);
Response.Cookies.Add(new HttpCookie(Product+"-ProductData", (new JavaScriptSerializer()).Serialize(model)));
return PartialView("~/Views/Product/_ProductData.cshtml", model);
}
}
I know that the Model is returned to the View as expected. The HTML from the partial shows up just fine. But it seems the cookie is not getting set by:
Response.Cookies.Add(new HttpCookie(Product+"-ProductData", (new JavaScriptSerializer()).Serialize(model)));
I cannot see the cookie in my browser's cookie storage location and the alert()
shows null
. I know that the JavaScriptSerializer
is working: I tested by putting the string in ViewData and displaying it on the page.
What am I doing wrong with respect to setting the cookie?
Upvotes: 2
Views: 2673
Reputation: 63588
There are limitations to the amount of data you can store in a cookie (and that amount varies by browser and browser version).
As we've determined in the comments above, setting a small value appears to work, so the serialization of a large value in the cookie is likely the issue.
@Iain's answer https://stackoverflow.com/a/4604212/6144 on the size limits of cookies appears to be fairly definitive so I'd suggest keeping within the limits he has noted there but the gist is:
"While on the subject, if you want to support most browsers, then do not exceed 50 cookies per domain, and 4093 bytes per domain. That is, the size of all cookies should not exceed 4093 bytes."
Upvotes: 1