2013-09-27 24 views
2

我在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?

+2

您的產品的JSON數據有多大?有一個大小限制(不同的瀏覽器/版本),你可能會超越設置它的挑戰。 – scunliffe

+0

我認爲就是這樣。我用「Some Value」取代了我的JSON,並且警報顯示「Some Value」。奇怪的是,我仍然沒有看到我的瀏覽器的臨時目錄中的cookie。 – Paul

+0

IE8的大小限制是4k。所以這絕對是它! – Paul

回答

1

您可以存儲在cookie中的數據量有限制(並且該數量因瀏覽器和瀏覽器版本而異)。

正如我們在上面的評論中所確定的那樣,設置一個小值似乎有效,所以cookie中大值的序列化可能是問題。

@伊恩有關Cookie的大小限制答案https://stackoverflow.com/a/4604212/6144似乎是相當明確的,因此我們建議的範圍內保持他注意到那裏,但要點是:

「雖然關於這個問題,如果你希望支持大多數瀏覽器,那麼每個域不要超過50個cookie,每個域不要超過4093個字節,也就是說,所有cookie的大小不應超過4093個字節。「