0

So far I made my site responsive without postback when adding products to cart( adds Product.Id to a cookie with JQuery).

When user visit the Cart/Checkout page, I read all Id's from cookie in Controllers and put all records into a cartList and pass it to the View.

Now I'm stuck as I don't know how to solve it without postback when I want to remove a product from the cart.

Is it possible to do something similar/corresponding like:

cartList.Remove(db.Products.SingleOrDefault(x=> x.Id == /*Id to remove from cart*/)); 

in View?

My code:

I added Product.Id into cookie with JQuery (gets id data-id="@item.ID" from foreach loop):

$('.add-to-cart').click(function () {

   if ($.cookie("AddedProductId") != null) {
      var previousValues = $.cookie("AddedProductId");
      $.cookie("AddedProductId", previousValues + '_' + $(this).data('id'));
   }else{
      $.cookie("AddedProductId", $(this).data('id'));
   }
 });

This is how I maintain cartList with added products, inside Controller when you visit cart/checkout page:

public ActionResult Cart(){

        var cart = Request.Cookies["AddedProductId"].Value;

        String[] elements = Regex.Split(cart, "_");          
        List<Product> cartList = new List<Product>();

        foreach (var item in elements){
            cartList.Add(db.Products.SingleOrDefault(x => x.ID == new Guid(item)));
        }    
        return View(cartList); 
}

I then display everything with a foreach loop inside /Cart/View.

What's the best option to solve this for Asp.Net MVC?

fagol
  • 209
  • 1
  • 3
  • 7

1 Answers1

0

A responsive website and the postback are different things.

Answering your question, a ajax request is a solution

in controller add:

[HttpPost]
public JsonResult Remove(Guid id)
{    
    cartList.RemoveAll(p => p.ID.Equals(id));

    return Json(new { removed = true });
}

jquery:

    $.ajax({
            url: '/Cart/Remove',
            type: 'POST',
            dataType: 'json',
            data: { id: <here selected ID> },
            success: function (json) {
                if(json.removed) {
                    // your code...
                }

            }
        });
Community
  • 1
  • 1
karritos
  • 344
  • 2
  • 9
  • I can't make it work, I even set breakpoint at my controller and it's not going to the `Remove` method. Also is this correct done: `data: $(this).data('id')`? What am I suppose to put in "`//your code...`" part? – fagol Nov 27 '16 at 16:44
  • Use `@Url.Action("Remove", "Cart")` method, this returns you the correct path you should use. Maybe your application is configured with an [application path](https://msdn.microsoft.com/en-us/library/system.web.httprequest.applicationpath(v=vs.110).aspx). In `//your code`, are the actions that will be carried out if it is eliminated in a correct way – karritos Nov 28 '16 at 18:59