gpt4 book ai didi

jquery - 在 ASP.NET MVC 3 中设置 cookie 中的 JSON 字符串

转载 作者:行者123 更新时间:2023-12-01 04:51:40 27 4
gpt4 key购买 nike

我在 ASP.NET MVC3 中有一个 View ,它调用 AsyncController 来获取部分 View 。我还想将一些数据作为 JSON 字符串设置到 cookie,以便我可以从 jQuery 读取。

这是我的观点:

$.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);
}
}

我知道模型已按预期返回到 View 。部分 HTML 显示得很好。但 cookie 似乎没有被设置:

Response.Cookies.Add(new HttpCookie(Product+"-ProductData", (new JavaScriptSerializer()).Serialize(model)));

我在浏览器的 Cookie 存储位置中看不到 Cookie,并且 alert() 显示 null。我知道 JavaScriptSerializer 正在工作:我通过将字符串放入 ViewData 并将其显示在页面上进行测试。

我在设置 cookie 方面做错了什么?

最佳答案

您可以在 Cookie 中存储的数据量存在限制(该数据量因浏览器和浏览器版本而异)。

正如我们在上面的评论中所确定的,设置一个较小的值似乎可行,因此 cookie 中较大值的序列化可能是问题所在。

@Iain 的回答 https://stackoverflow.com/a/4604212/6144关于 cookie 大小的限制似乎相当明确,因此我建议保持在他在那里指出的限制范围内,但要点是:

"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."

关于jquery - 在 ASP.NET MVC 3 中设置 cookie 中的 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19057499/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com