【发布时间】: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