简体   繁体   中英

why these cookie codes didn't work in asp.net mvc?

I'm developing an asp.net mvc 5 online store project . I want to create cart to add Goods with Cookie . I'm confused about it and don't know why it didn't work . it didn't gave me any error . also I add break points to debug it but any data didn't send to my actions ! could anyone help me ? what's the problem ? I'm not good in javascript and I think problem would be in javascript codes :/ Thanks in advance

Goods 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);
            }
            int CartCount = Request.Cookies.AllKeys.Where(p => p.StartsWith("NishtmanCart_")).Count();
            return Json(new MyJsonData()
            {
                Success = true,
                Script = MessageBox.Show("product added to your basket", MessageType.Success).Script,
                Html = "Shopping Cart (" + CartCount.ToString() + ")"
            });
        }
        catch (Exception)
        {
            return Json(new MyJsonData()
            {
                Success = false,
                Script = MessageBox.Show("product didn't add to your basket", MessageType.Error).Script,
                Html = ""
            });
        }
    }

    public ActionResult RemoveCart(int Id)
    {

        try
        {
            int CartCount = Request.Cookies.AllKeys.Where(p => p.StartsWith("NishtmanCart_")).Count();

            if (Request.Cookies.AllKeys.Contains("NishtmanCart_" + Id.ToString()))
            {
                Request.Cookies["NishtmanCart_" + Id.ToString()].Expires = DateTime.Now.AddDays(-1);
                return Json(new MyJsonData()
                {
                    Success = true,
                    Script = MessageBox.Show("product removed from your basket", MessageType.Success).Script,
                    Html = "Shopping Cart (" + CartCount.ToString() + ")"
                });
            }
            else
            {
                return Json(new MyJsonData()
                {
                    Success = false,
                    Script = MessageBox.Show("this product doesn't have in your basket", MessageType.Warning).Script,
                    Html = "Shopping Cart (" + CartCount.ToString() + ")"
                });
            }
        }
        catch (Exception)
        {
            return Json(new MyJsonData()
            {
                Success = true,
                Script = MessageBox.Show("product didn't remove from your basket", MessageType.Error).Script,
                Html = ""
            });
        }

    }

MyJsonData.cs

public class MyJsonData
{
    public string Script { get; set; }
    public string Html { get; set; }
    public bool Success { get; set; }
}

_GoodDetailsAjax.cshtml

 @foreach (var item in Model.GoodDetails)
{
  <div>
       <p class="nowprice">NowPrice : @item.DetailsNowPrice</p>
       <p class="preprice">PrePrice : @item.DetailsPrePrice</p>
        <a class="button icon-cart" href="#" GoodID="@item.DetailsGoodID">Add to cart</a><br>
        <a class="link" >Shopping Cart (0)</a>
    </div>
}
 @section scripts{
<script src="~/Scripts/jquery-2.1.4.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script>
    $(function () {
        $("a.button.icon-cart").click(function (e) {
            e.preventDefault();
            var goodId = $(this).attr("GoodID");
            alert(goodId); //////// I just added this code
            $.ajax({
                url: "/Goods/AddToCart",
                data: { Id: goodId, Count: 1 },
                type: "Post",
                dataType: "Json",
                success: function (result) {
                    if (result.Success) {
                        $("#CartItems").html(result.Html);
                    }
                    eval(result.Script);
                },
                error: function () {
                    alert("Error!");
                }
            });
        });
    });
</script>
 }

I don't know what's the implementation of MessageBox.Show("....", MessageType.Error).Script but I'm assuming that it just generates a simple JavaScript statement like this:

Script = "alert('product added to your basket');"

So you can add this tag for the result:

<div id="CartItems">

</div>

Now it works without any problem.

All of my codes was true , I just made some simple mistakes .

I loaded a JQuery file in my layout and also I loaded another version of JQuery in my view! I deleted one of them .

And also I used those codes in a partial view and loaded they using Ajax but my partial view couldn't pass data to Controller , I moved codes to main view ( GoodDetails.cshtml ) and it works fine now .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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