public void AddToCart(Course cohort) { // Get the matching cart and Product instances var cartItem = _db.Carts.SingleOrDefault( c => c.CartId == ShoppingCartId && c.CourseId == cohort.Id); if (cartItem == null) { // Create a new cart item if no cart item exists cartItem = new Cart { CourseId = cohort.Id, CartId = ShoppingCartId, Count = 1, DateCreated = DateTime.Now }; _db.Carts.Add(cartItem); } else { // If the item does exist in the cart, // then add one to the quantity cartItem.Count++; } // Save changes _db.SaveChanges(); }
public ActionResult ProductsList(Cart model, FormCollection form) { if (form.Keys.Count != 0) // if input exists { for (var i = 0; i < form.Keys.Count; ++i) { string name = form.GetKey(i); if (name.Contains("delete")) { var id = name.Substring(name.IndexOf('_') + 1, name.Length - 1 - name.IndexOf('_')); var product = _dataManager.Products.GetProductById(Convert.ToInt32(id)); GetCart().RemoveItem(product); if (GetCart().IsEmpty) { ViewBag.IsAddToCart = null; Session["Cart"] = null; } else { Session["Cart"] = GetCart(); } break; } } } if (Session["Cart"] == null) { ViewBag.CartIsEmpty = true; return View("ProductsList", null); } return View("ProductsList", new CartViewModel { Cart = GetCart() }); }
private Cart GetCart() { var cart = (Cart)Session["Cart"]; if (cart == null) { cart = new Cart(); Session["Cart"] = cart; } return cart; }
private bool OrderService(Cart cart, CartViewModel resultModel) { var time = DateTime.Now; foreach (var item in cart.Lines) { var product = _dataManager.Products.GetProductById(item.Product.Id); var productsCustomers = _dataManager.ProductsCustomers.GetProductsCustomersByProductId(item.Product.Id); if (product == null || productsCustomers == null) return false; int newCount, purchaseCount; if (item.Quantity < productsCustomers.Count) { newCount = productsCustomers.Count - item.Quantity; purchaseCount = item.Quantity; } else { newCount = 0; purchaseCount = productsCustomers.Count; } if (!_dataManager.Orders.AddNewOrder((int) Session["UserId"], item.Product.Id, time, purchaseCount)) continue; if (!_dataManager.ProductsCustomers.UpdateProdCastRelation(item.Product.Id, newCount)) _dataManager.Orders.DeleteOrder((int) Session["UserId"], (int) Session["CurrentProductId"], time); if (newCount == 0) { product.IsAvailable = false; _dataManager.Products.UpdateProduct(product); } resultModel.Cart.AddItem(item.Product, item.Quantity); } return true; }