public int AddToCart(int productId, string name, decimal price)
        {
            var userId = GetUserId();

            if (userId != 0)
            {
                using (var entities = new AngularBootcampEntities())
                {
                    var existingCartItem = entities.UserCartItems.FirstOrDefault(x => x.UserId == userId && x.ProductId == productId);

                    if (existingCartItem == null)
                    {
                        UserCartItem cartItem = new UserCartItem
                        {
                            ProductId = productId,
                            UserId = userId,
                            ProductName = name,
                            Price = price,
                            Count = 1
                        };
                        entities.UserCartItems.Add(cartItem);
                    }
                    else
                    {
                        existingCartItem.Count++;
                    }

                    entities.SaveChanges();
                }
            }
            return userId;
        }
Example #2
0
        public async Task CreateAsync(string userId, int gameId)
        {
            var cartItem = new UserCartItem
            {
                UserId = userId,
                GameId = gameId,
            };

            await this.userCartItemsRepository.AddAsync(cartItem);

            await this.userCartItemsRepository.SaveChangesAsync();
        }
        public async Task <ActionResult> Add(string id)
        {
            var userId = User.Identity.GetUserId();

            if (db.UserCartItems.Any(c => c.UserId == userId && c.GameId == id))
            {
                // add displaying errors to the home page
                //return RedirectToAction("ViewGame", "Home", new { area = "" });
                TempData["message"] = "This game is already in your cart.";
                return(RedirectToAction("ViewGame", new RouteValueDictionary(new { controller = "Home", action = "ViewGame", Id = id })));
            }

            var newCartItem = new UserCartItem()
            {
                UserId = userId, GameId = id
            };

            db.UserCartItems.Add(newCartItem);
            await db.SaveChangesAsync();

            Session["cart"] = db.UserCartItems.Where(c => c.UserId == userId).Count().ToString();
            return(RedirectToAction("ViewGame", new RouteValueDictionary(new { controller = "Home", action = "ViewGame", Id = id })));
        }