简体   繁体   English

如何在ASP.NET MVC中管理Cookie项的顺序(顺序)?

[英]How manage order(sequence) of cookie items in asp.net mvc?

I'm working on asp.net mvc5 project . 我正在asp.net mvc5项目上。 I have a page for show cart items , and used cookie for save items . 我有一个页面显示cart items ,并使用cookie保存物品。 But I have a problem with order of cart items , when I changed number of cart items , the order(sequence) changed . 但是我order of cart items ,当我更改购物车商品的数量时,订单(顺序)发生了变化。 I don't want it I think it's not good . 我不要,我认为这不好。 I know it's because of cookie but I don't know how fix it . 我知道这是因为Cookie,但我不知道如何解决。 Could anyone help me please? 有人可以帮我吗?

Javascript Java脚本

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

Good Cotroller 好主妇

 [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 = ""
            }
                );
        }
    }

There is number of cart items in textbox that saved in cookie , when I changed this number , sequence changed . 文本框中有许多购物车项目已保存在cookie中,当我更改此数字时,顺序发生了变化。 How I prevent this ? 我该如何预防? 在此处输入图片说明

This is totally unnecessary. 这完全没有必要。 You are using [HttpPost] which means it won't be a GET method. 您正在使用[HttpPost],这意味着它不是GET方法。

bool isGet = Request.HttpMethod == "GET"

Also your HTML above doesn't match your output. 另外,您上面的HTML与您的输出不匹配。 We'd need to see what makes up MyJsonOutput for Html = "Cart Items (" + CartCount.ToString() + ")" 我们需要查看由Html =“ Cart Items(” + CartCount.ToString()+“)”构成MyJsonOutput的原因

Without seeing that what I'm guessing here is you: 1. Change the qty and submit it. 在没有看到我在想你的情况下:1.更改数量并提交。 2. Your AddToCart method checks if the Id is there and then updates the response cookies.I'm assuming this then sends a set-cookie request to the browser and changes your order. 2.您的AddToCart方法检查ID是否存在,然后更新响应cookie。我假设这随后将set-cookie请求发送到浏览器并更改您的订单。

for (int i = 0; i < Request.Cookies.Count; i++ )
{
    lst.Add(Request.Cookies[i]);
}

To something like this that sorts the keys 像这样对键进行排序

foreach (var cookie in Response.Cookies.AllKeys.OrderBy(o => o))
{
    lst.Add(Request.Cookies[cookie]);
}

With that said you may want to rethink this approach and not use cookies but instead just post the form each time and parse the data - ex In MVC4, how to save multiple row edits at once? 话虽如此,您可能想重新考虑这种方法,而不是使用Cookie,而是每次仅发布表单并解析数据-例如在MVC4中,如何一次保存多个行编辑? and Posting serialized form data AND additional data to MVC controller? 并将序列化的表格数据和其他数据发布到MVC控制器? in those cases you are using AJAX to send all the data to the server, bind it into a nice model and work with it. 在这种情况下,您将使用AJAX将所有数据发送到服务器,将其绑定到一个不错的模型中并使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM