private void AddNewItemsToCart(string userId, string session_UserId)        // session_UserId should be the real user ID converteid to from int to string
        {
            List <CartItem> cart = db.Cart.Where(x => x.UserId == userId).ToList(); // userId should be the DeviceName

            foreach (CartItem item in cart)
            {
                item.UserId = session_UserId;
                db.Update(item);
                db.SaveChanges();
            }
        }
예제 #2
0
        //receive JSON data from Add.js. (When an item is added to the cart from gallery)
        public JsonResult AddItemToCart([FromBody] Addinput product)
        {
            string sessionId; try { sessionId = HttpContext.Request.Cookies["sessionId"]; } catch (NullReferenceException) { sessionId = null; }
            string userId; if (sessionId != null)

            {
                userId = HttpContext.Request.Cookies["userId"];
            }
            else
            {
                userId = Environment.MachineName;
            }

            CartItem item = db.Cart.FirstOrDefault(x => x.UserId == userId && x.pId == product.ProductId);

            if (item == null)
            {
                item = new CartItem();

                item.UserId   = userId;
                item.pId      = product.ProductId;
                item.Quantity = 1;
                item.product  = db.Products.FirstOrDefault(x => x.ProductId == int.Parse(product.ProductId));
                db.Add(item);
            }
            else
            {
                item.Quantity += 1;
                db.Update(item);
            }

            db.SaveChanges();

            List <CartItem> cart = db.Cart.Where(x => x.UserId == userId).ToList();

            int total = 0;

            foreach (CartItem x in cart)
            {
                total += x.Quantity;
            }

            return(Json(new
            {
                status = "success",
                total = total
            }));
        }