我在ASP.NET MVC3中有一個視圖,它調用AsyncController來獲取局部視圖。我也想將一些數據設置爲一個JSON字符串到我可以從jQuery讀取的cookie。在ASP.NET MVC中設置cookie中的JSON字符串3
這是我的觀點:
$.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);
}
});
這裏是我的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);
}
}
我知道按照預期模式返回到視圖。來自部分的HTML顯示得很好。但似乎cookie不會得到通過設置:
Response.Cookies.Add(new HttpCookie(Product+"-ProductData", (new JavaScriptSerializer()).Serialize(model)));
我看不到我的瀏覽器的cookie存儲位置的餅乾和alert()
顯示null
。我知道JavaScriptSerializer
正在工作:我通過將字符串放在ViewData中並將其顯示在頁面上進行測試。
我在做錯誤的方面設置cookie?
您的產品的JSON數據有多大?有一個大小限制(不同的瀏覽器/版本),你可能會超越設置它的挑戰。 – scunliffe
我認爲就是這樣。我用「Some Value」取代了我的JSON,並且警報顯示「Some Value」。奇怪的是,我仍然沒有看到我的瀏覽器的臨時目錄中的cookie。 – Paul
IE8的大小限制是4k。所以這絕對是它! – Paul