我正在开发 asp.net mvc5 项目。我有一个用于显示购物车项目的页面,并使用 cookie 来保存项目。但是我的购物车商品顺序有问题,当我更改购物车商品数量时,顺序(序列)发生了变化。我不想这样,我觉得这样不好。我知道这是因为cookie,但我不知道如何解决它。有人可以帮我吗?
Javascript
$(function () {
alert("aleeeert");
$(".textCountProduct").change(function () {
var count = $(this).val();
var id = $(this).attr("productid");
alert(count);
alert(id);
$.ajax({
url: "/Goods/AddToCart",
data: { Id: id, Count: count },
type: "Post",
dataType: "Json",
success: function (result) {
if (result.Success) {
alert(result.Html);
$("#CartItems").html(result.Html);
}
eval(result.Script);
},
error: function () {
alert("error....");
}
});
});
});
良好的 Controller
[HttpPost]
public ActionResult AddToCart (int Id , int Count)
{
try
{
if (Request.Cookies.AllKeys.Contains("NishtmanCart_" + Id.ToString()))
{
//Edit cookie
var cookie = new HttpCookie("NishtmanCart_" + Id.ToString(), (Convert.ToInt32(Request.Cookies["NishtmanCart_" + Id.ToString()].Value) + 1).ToString());
cookie.Expires = DateTime.Now.AddMonths(1);
cookie.HttpOnly = true;
Response.Cookies.Set(cookie);
}
else
{
//Add new cookie
var cookie = new HttpCookie("NishtmanCart_" + Id.ToString(), Count.ToString());
cookie.Expires = DateTime.Now.AddMonths(1);
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
}
List<HttpCookie> lst = new List<HttpCookie>();
for (int i = 0; i < Request.Cookies.Count; i++ )
{
lst.Add(Request.Cookies[i]);
}
bool isGet = Request.HttpMethod == "GET";
int CartCount = lst.Where(p => p.Name.StartsWith("NishtmanCart_") && p.HttpOnly != isGet).Count();
return Json(new MyJsonData()
{
Success = true,
Script = MessageBox.Show("Good added suucessfully", MessageType.Success).Script,
Html = "Cart Items (" + CartCount.ToString() + ")"
}
);
}
catch(Exception)
{
return Json(new MyJsonData()
{
Success = false,
Script = "alert('Good didn't add');",
Html = ""
}
);
}
}
最佳答案
这是完全没有必要的。您正在使用 [HttpPost],这意味着它不是 GET 方法。
bool isGet = Request.HttpMethod == "GET"
此外,您上面的 HTML 与您的输出不匹配。我们需要了解 Html 的 MyJsonOutput = "Cart Items ("+ CartCount.ToString() + ")"
没有看到我在这里猜测的是你: 1. 更改数量并提交。 2. 您的 AddToCart 方法检查 Id 是否存在,然后更新响应 cookie。我假设这会向浏览器发送 set-cookie 请求并更改您的订单。
for (int i = 0; i < Request.Cookies.Count; i++ ) { lst.Add(Request.Cookies[i]); }
像这样对键进行排序
foreach (var cookie in Response.Cookies.AllKeys.OrderBy(o => o)) { lst.Add(Request.Cookies[cookie]); }
话虽如此,您可能想重新考虑这种方法,而不是使用 cookie,而是每次发布表单并解析数据 - 例如 In MVC4, how to save multiple row edits at once? 和 Posting serialized form data AND additional data to MVC controller? 在这些情况下,您将使用 AJAX 将所有数据发送到服务器,将其绑定(bind)到一个好的模型中并使用它。
关于javascript - 如何在asp.net mvc中管理cookie项的顺序(序列)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34960728/