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

标签 jquery asp.net-mvc-3 cookies

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

相关文章:

javascript - tinyMCE 在外面点击,textarea 隐藏

jQuery 链接 - 我可以编写更清晰的代码吗?

php - 以数字开头命名 cookie 可以吗?

php - 用 JavaScript 编写的 Cookie 在 PHP 中仅显示为整数

jquery - 页面宽度超过屏幕宽度的100%

JQuery 切换多个 Div + 阅读更多/阅读更少

asp.net-mvc - 具有嵌套 View 模型的自定义 ModelBinder

c# - 提供下载链接而不在服务器上创建文件

c# - 如何在 MVC 3 aspx 引擎中使用方法以及如何在 mvc 3 中使用中继器控件?

javascript - HTTP 响应中的意外内容