Пример #1
0
        // Adding the item to cart
        public async Task <IActionResult> Add(int listingId, string userId)
        {
            string url = "/Accounts/Login";

            if (userId == null)
            {
                return(LocalRedirect(url));
            }


            // Find the cart associated with this account
            var cartContext = await _context.Cart
                              .Where(s => s.TransactionComplete == false)
                              .FirstOrDefaultAsync(s => s.AccountId.ToString() == userId);

            // If the account does not have a cart associated with them, create one
            if (cartContext == null)
            {
                await CreateCart(userId);

                cartContext = await _context.Cart.
                              Where(s => s.TransactionComplete == false)
                              .FirstOrDefaultAsync(s => s.AccountId.ToString() == userId);
            }

            // Does this item already exist in this cart?
            var itemContext = await _context.ItemsForCart
                              .Where(s => s.CartId == cartContext.CartId)
                              .FirstOrDefaultAsync(s => s.SellListingId == listingId);

            if (itemContext == null)
            {
                ItemsForCart item = new ItemsForCart();
                item.CartId        = cartContext.CartId;
                item.SellListingId = listingId;
                item.Quantity      = 1;

                if (ModelState.IsValid)
                {
                    _context.Add(item);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
            }
            else
            {
                // Find the associated cart item
                itemContext.Quantity++;
                _context.Update(itemContext);
                await _context.SaveChangesAsync();
            }

            return(RedirectToAction("Index"));
        }
Пример #2
0
        public List <ItemsForCart> Cart()
        {
            SellListing  sellListing = Product();
            ItemsForCart product     = new ItemsForCart
            {
                SellListing = sellListing,
                Quantity    = 1
            };
            List <ItemsForCart> cart = new List <ItemsForCart>();

            cart.Add(product);
            return(cart);
        }