0

I'm working on asp.net mvc5 project . I have a page for show cart items, and used cookie for save items . But I have a problem with order of cart items , when I changed number of cart items , the order(sequence) changed . 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 . Could anyone help me please?

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

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 . How I prevent this ? enter image description here

shm
  • 439
  • 2
  • 11
  • 25

1 Answers1

1

This is totally unnecessary. You are using [HttpPost] which means it won't be a GET method.

 bool isGet = Request.HttpMethod == "GET"

Also your HTML above doesn't match your output. We'd need to see what makes up MyJsonOutput for Html = "Cart Items (" + CartCount.ToString() + ")"

Without seeing that what I'm guessing here is you: 1. Change the qty and submit it. 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.

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? and Posting serialized form data AND additional data to MVC controller? 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.

Community
  • 1
  • 1
Adam Tuliper
  • 29,982
  • 4
  • 53
  • 71