【问题标题】:unable to get updated cookie value in jquery after ajax callajax调用后无法在jquery中获取更新的cookie值
【发布时间】:2014-11-26 06:00:57
【问题描述】:

我在 mvc 中做了一个简单的购物车示例。 我正在做的是,点击Add to cart span 后,我正在调用一个Controller Action 方法。

然后使用购物车中的商品总数更新 cookie 值。但它给了我 cookie 的初始值。

这是我调用控制器动作的 Ajax 代码

   $(document).delegate('.addCart','click', function () {
            var getId = parseInt($(this).attr('id').slice(3));
            $.ajax({
                type: 'GET',
                contentType: 'application/json; charset=utf-8',
                url: '/Comments/CartDetailsSetGet',
                data: { Id: getId },
                success: function (data) {
                    var count = parseInt(data);
                    if (isNaN(count)){
                        alert(data);
                    }else{
                        var getCookies=  @HttpContext.Current.Request.Cookies["CartCookie"].Value;
                        $('.cartNum').html(getCookies);
                    }
                },
                error: function (data) {
                    alert("Error In Adding Item To Cart");
                }
            });
        });

span > with class cartNum,我在其中显示购物车中的商品总数。

addCart 是我单击以将项目添加到购物车的跨度。

这是我的动作方法,这是我的默认动作

HttpCookie ck = new HttpCookie("CartCookie");
        public ActionResult Index()
        {
            if (Request.Cookies["CartCookie"] == null)
            {
                ck.Value = "0";
                Response.SetCookie(ck);
            }
            IList<Comment> commentList = db.Comments.ToList();
            return View(commentList);
        }

在 Ajax 请求时调用此操作。

static List<int?> CartItemsId = new List<int?>();
        public string CartDetailsSetGet(int? Id)
        {
              if (CartItemsId.Contains(Id) != true)
                {
                    CartItemsId.Add(Id);
                    int getCount = CartItemsId.Count();
                    System.Web.HttpContext.Current.Request.Cookies["CartCookie"].Value = getCount.ToString();
                    ck.Expires = DateTime.Now.AddDays(-1);
                    var d = "";
                    if (System.Web.HttpContext.Current.Request.Cookies["CartCookie"] != null)
                    {
                        d = System.Web.HttpContext.Current.Request.Cookies["CartCookie"].Value;
                    }
                    return d.ToString();
                }
                else
                {
                    return "This Item Is Already In Cart";
                }            
        }

d 中,我正在获取更新的 cookie 值,但在 Ajax Success 中,这一行给了我初始值,即 0。

var getCookies= @HttpContext.Current.Request.Cookies["CartCookie"].Value;

【问题讨论】:

  • var getCookies= '@HttpContext.Current.Request.Cookies["CartCookie"].Value'; 是剃须刀代码,在页面发送到浏览器之前呈现在服务器端
  • @StephenMuecke:那么我应该怎么做才能在我的视图中获得更新的 cookie 值。这样即使用户在看到更新的 cookie 值时也会刷新页面。
  • 在您的 CartDetailsSetGet 方法中,您可以返回包含所需值的 JSON
  • @StephenMuecke:我可以这样做,但是如果在添加一些项目后,用户刷新页面,那么这个方法将不会被调用,并且用户看不到总数,因为尽快当他刷新页面时,我的 index Action 将被调用。
  • 不,我的意思是 public JsonResult CartDetailsSetGet(int? Id) { var data = new { itemCount = 2, message = "some message" }; return Json(data); } 然后在 ajax 成功,$('.cartNum').html(data.itemCount);

标签: jquery asp.net ajax asp.net-mvc cookies


【解决方案1】:

在您的脚本中,var getCookies = '@HttpContext.Current.Request.Cookies["CartCookie"].Value' 是剃须刀代码,在成为浏览器之前先解析服务器端。如果您检查页面源,您会看到 getCookies 的值已设置为“0”。

与其尝试设置或更新 cookie,不如在包含您要呈现的值的 CartDetailsSetGet 中返回 JSON 数据,例如

public JsonResult CartDetailsSetGet(int? Id)
{
  if (CartItemsId.Contains(Id) != true)
  {
    ....
    int getCount = CartItemsId.Count();
    var data = new { count = getCount , message = "some message" };
    return Json(data, JsonRequestBehavior.AllowGet);
  }
  {
    var data = new { count = null, message = "This Item Is Already In Cart" };
    return Json(data, JsonRequestBehavior.AllowGet);
  }
}

脚本

$.ajax({
  ....
  success: function (data) {
    if (data.count) {
      $('.cartNum').html(data.count);
    } else {
      alert(data.message);
    }
  },
  ....

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-27
    • 1970-01-01
    • 1970-01-01
    • 2014-10-18
    相关资源
    最近更新 更多