Ejemplo n.º 1
0
        /// <summary>
        /// Deletes an row in the Cart
        /// </summary>
        /// <param name="search">ID</param>
        /// <returns></returns>
        public ActionResult Delete(int search)
        {
            var context      = new AppDbContext();
            int affectedRows = 0;
            var ca           = context.Carts.FirstOrDefault(x => x.ID == search);

            var cart2 = new CartVM();

            if (ca != null)
            {
                cart2.ID              = ca.ID;
                cart2.ItemName        = "Deleted";
                cart2.ItemDescription = " ";
                cart2.Price           = 0;
                cart2.Quantity        = 0;

                context.Carts.Remove(ca);
                affectedRows = context.SaveChanges();
            }

            if (affectedRows > 0)
            {
                ViewBag.Message = "Cart " + search + " deleted.";
                //   return RedirectToAction("Index", "Home");
                return(PartialView("_shopCart", cart2));
            }
            else
            {
                ViewBag.Message = "Something went wrong!";
                //  return View();
                return(PartialView("_shopCart", cart2));
            }
        }
Ejemplo n.º 2
0
        public ActionResult CartPartial()
        {
            //Init the CartVM
            CartVM model = new CartVM();
            //Init quantity
            int qty = 0;
            //Init price
            decimal price = 0m;

            //Check for cart session
            if (Session["cart"] != null)
            {
                //Get total qty and price
                var list = (List <CartVM>)Session["cart"];

                foreach (var item in list)
                {
                    qty   += item.Quantity;
                    price += item.Quantity * item.Price;
                }

                model.Quantity = qty;
                model.Price    = price;
            }
            else
            {
                //Or set qty and price to 0
                model.Quantity = 0;
                model.Price    = 0m;
            }

            //Return partial view with model
            return(PartialView(model));
        }
        // GET: /Cart/DecrementProduct
        public ActionResult DecrementProduct(int productId)
        {
            // Init cart
            List <CartVM> cart = Session["cart"] as List <CartVM>;

            using (Db db = new Db())
            {
                // Get model from list
                CartVM model = cart.FirstOrDefault(x => x.ProductId == productId);

                // Decrement qty
                if (model.Quantity > 1)
                {
                    model.Quantity--;
                }
                else
                {
                    model.Quantity = 0;
                    cart.Remove(model);
                }

                // Store needed data
                var result = new { qty = model.Quantity, price = model.Price };

                // Return json
                return(Json(result, JsonRequestBehavior.AllowGet));
            }
        }
Ejemplo n.º 4
0
        public ActionResult OrderList(CartVM vm)
        {
            int userId = (int)Session[CDictionary.SK_LOGINED_USER_ID];

            var currentCart = db.OrderList
                              .Where(m => m.oId == vm.oId && m.cId == vm.cId).ToList();


            if (currentCart != null)
            {
                foreach (var item in currentCart)
                {
                    item.oQty += vm.orderQty;
                }


                db.SaveChanges();



                return(Json(vm));

                // return RedirectToAction("OrderList", "Order");
            }
            //currentCart.oQty += vm.orderQty;
            //db.SaveChanges();
            return(RedirectToAction("ProductList", "Product"));
            //  return RedirectToAction("OrderList", "Order");
        }
Ejemplo n.º 5
0
        public ActionResult CartPartial()
        {
            CartVM model = new CartVM();

            int     qty   = 0;
            decimal price = 0m;

            if (Session["cart"] != null)
            {
                var list = (List <CartVM>)Session["cart"];

                foreach (var item in list)
                {
                    qty   += item.Quantity;
                    price += item.Quantity * item.Price;
                }

                model.Quantity = qty;
                model.Price    = price;
            }
            else
            {
                model.Quantity = 0;
                model.Price    = 0m;
            }
            return(PartialView("_CartPartial", model));
        }
Ejemplo n.º 6
0
        public ActionResult AddToCart(int id)
        {
            //string SK = fc["txtSL"].ToString();
            var _Product = db.Products.Find(id);
            var CartList = new List <CartVM>();

            if (Session["Cart"] != null)
            {
                CartList = (List <CartVM>)Session["Cart"];
                var OldCart = CartList.Find(m => m.Product.ProductID == id);//OldCart.Quantity + 1
                if (OldCart != null)
                {
                    var NewCart = new CartVM {
                        Product = _Product, Quantity = 1
                    };
                    CartList.Remove(OldCart);
                    CartList.Add(NewCart);
                }
                else
                {
                    CartList.Add(new CartVM {
                        Product = _Product, Quantity = 1
                    });
                }
            }
            else
            {
                CartList.Add(new CartVM {
                    Product = _Product, Quantity = 1
                });
            }
            Session["Cart"] = CartList;
            return(RedirectToAction("ShowCart"));
        }
        //partial view za cart
        public ActionResult CartPartialView()
        {
            //Inicijalizovati CartVM
            CartVM model = new CartVM();
            //Inicijalizovati kolicinu(Quantity)
            int quantity = 0;
            //Inicijalizacija cene(Price)
            decimal price = 0m;

            //Proveriti da li postoji session cart
            if (Session["cart"] != null)
            {
                //Pronaci kolika je ukupna vrednost(Total) i cena (Price)
                var list = (List <CartVM>)Session["cart"];

                foreach (var item in list)
                {
                    quantity += item.Quantity;
                    price    += item.Price * item.Quantity;
                }
                model.Quantity = quantity;
                model.Price    = price;
            }
            else
            {
                // postaviti quantity and price na 0
                model.Quantity = 0;
                model.Price    = 0m;
            }

            //vratiti partial view sa modelom
            return(PartialView(model));
        }
Ejemplo n.º 8
0
        public async Task <ActionResult> SetCoupon(string uniqueId)
        {
            CartVM cart = (CartVM)Session["Cart"];

            cart.CouponUniqueId = "";
            foreach (var p in cart.Products)
            {
                p.Discount = 0;
            }
            var c = db.GetCouponInfo(uniqueId);

            if (c == null)
            {
                return(Json("error", JsonRequestBehavior.AllowGet));
            }
            cart.CouponUniqueId = uniqueId;

            List <ProductDiscountVM> result = new List <ProductDiscountVM>();

            foreach (var p in cart.Products)
            {
                ProductVM prd = await db.Get(p.ProductId);

                if (c.ForAll || c.HCategoryId == prd.HCategoryId || c.VCategoryId == prd.VCategoryId || c.ProductId == prd.ProductId)
                {
                    p.Discount = c.Discount;
                    result.Add(new ProductDiscountVM()
                    {
                        ProductId = prd.ProductId,
                        Discount  = c.Discount
                    });
                }
            }
            return(Json(result.ToArray(), JsonRequestBehavior.AllowGet));
        }
Ejemplo n.º 9
0
        public async Task <ActionResult> Checkout()
        {
            int customerId = -1;

            if (Session["CustomerId"] != null)
            {
                customerId    = (int)Session["CustomerId"];
                ViewBag.login = false;
            }
            else
            {
                ViewBag.login = true;
            }
            var model = db.GetLastCheckoutData(customerId);

            model.Countries = db.GetCountries();
            CartVM cart = (CartVM)Session["Cart"];

            model.BillingCountryId  = cart.CountryId;
            model.DeliveryCountryId = cart.CountryId;
            model.Details           = cart.Products;
            model.DeliveryPrice     = cart.CountryPrice;

            if (model.CustomerName == null)
            {
                var cmr = await db.GetCustomer(customerId);

                model.BillingCountryId = cmr.CountryId;
                model.CustomerEmail    = cmr.Username;
                model.CustomerName     = cmr.CustomerName;
            }

            return(View(model));
        }
Ejemplo n.º 10
0
        public ActionResult <CartVM> UpdateShippingProvider([FromBody] ShippingProviderVM shippingProvider)
        {
            _logger.LogInformation($"*** Update paymentprovider in cart to {shippingProvider.ShippingMethod} ***");

            CartVM cart =
                HttpContext.Session.Get <CartVM>("_Cart") ??
                new CartVM();

            if (cart.CartId == null)
            {
                cart.CartId = Guid.NewGuid().ToString();
            }

            if (shippingProvider.ShippingMethod != null)
            {
                cart.ShippingMethod = (ShippingType)Enum.Parse(typeof(ShippingType), shippingProvider.ShippingMethod);
            }

            // Update shipping cost
            cart.ShippingCost = GetShippingCost(cart);

            // Save Cart to session
            HttpContext.Session.Set <CartVM>("_Cart", cart);

            return(Ok(cart));
        }
Ejemplo n.º 11
0
        public CartVM getCart(string id)
        {
            int SeatInfoId = _db.Users.Where(u => u.Id == id).FirstOrDefault().SeatInfo.Id;

            CartVM vm = _db.Orders
                        .Where(o => o.SeatInfoId == SeatInfoId && !o.IsRetired && o.TimeOrdered == null)
                        .Select(o => new CartVM
            {
                Items = o.OrderItems.Where(i => !i.IsRetired).Select(i => new ItemVM
                {
                    Id          = i.Item.Id,
                    Name        = i.Item.Name,
                    ImageUrl    = i.Item.ImageUrl,
                    Description = i.Item.Description,
                    Price       = i.Item.Price,
                    Discount    = i.Item.Discount,
                    Quantity    = i.Quantity,
                    IsAlcohol   = i.Item.IsAlcohol
                }).ToList(),
                Subtotal       = o.Subtotal,
                Taxes          = o.Taxes,
                ConvenienceFee = o.ConvenienceFee,
                OutOfAreaFee   = o.OutOfAreaFee,
                Total          = o.Total,
                PersDesc       = o.PersDesc,
                TimeOrdered    = o.TimeOrdered,
                TimePrepared   = o.TimePrepared,
                TimeDelivered  = o.TimeDelivered
            }).FirstOrDefault();

            return(vm);
        }
Ejemplo n.º 12
0
        public ActionResult <CartVM> UpdateCustomer([FromBody] CartCustomerInfo customer)
        {
            _logger.LogInformation("*** Add customer to cart ***");
            if (customer == null)
            {
                return(BadRequest());
            }

            CartVM cart =
                HttpContext.Session.Get <CartVM>("_Cart") ??
                new CartVM();

            if (cart.CartId == null)
            {
                cart.CartId = Guid.NewGuid().ToString();
            }

            var cartCustomer = new CartCustomerInfo()
            {
                Name    = customer.Name,
                Email   = customer.Email,
                Address = customer.Address,
                Zip     = customer.Zip,
                City    = customer.City,
                Country = customer.Country
            };

            cart.Customer = cartCustomer;

            // Save Cart to session
            HttpContext.Session.Set <CartVM>("_Cart", cart);

            return(cart);
        }
Ejemplo n.º 13
0
        public ActionResult Cancel(int id = 0)
        {
            var context = new AppDbContext();
            var cart2   = new CartVM();

            var ca = context.Carts.FirstOrDefault(x => x.ID == id);

            if (ca != null)
            {
                cart2.ID          = ca.ID;
                cart2.CartId      = ca.CartId;
                cart2.ItemId      = ca.ItemId;
                cart2.Price       = ca.Price;
                cart2.Quantity    = ca.Quantity;
                cart2.DateCreated = ca.DateCreated;

                var product = context.Items.FirstOrDefault(x => x.ItemId == ca.ItemId);
                if (product != null)
                {
                    cart2.ItemName        = product.Name;
                    cart2.ItemDescription = product.Description;
                }
            }

            return(PartialView("_shopCart", cart2));
        }
Ejemplo n.º 14
0
        public ActionResult Edit([Bind(Include = "ID, ItemName, ItemDescription, Price, Quantity")] CartVM p)
        {
            var context = new AppDbContext();
            var ca      = context.Carts.FirstOrDefault(x => x.ID == p.ID);

            if (ModelState.IsValid && ca != null)
            {
                ca.Quantity = p.Quantity;
                var affectedRows = context.SaveChanges();

                return(PartialView("_shopCart", p));
            }
            else
            {
                var cart2 = new CartVM();

                if (ca != null)
                {
                    cart2.ID          = ca.ID;
                    cart2.CartId      = ca.CartId;
                    cart2.ItemId      = ca.ItemId;
                    cart2.Price       = ca.Price;
                    cart2.Quantity    = ca.Quantity;
                    cart2.DateCreated = ca.DateCreated;
                    var product = context.Items.FirstOrDefault(x => x.ItemId == ca.ItemId);
                    if (product != null)
                    {
                        cart2.ItemName        = product.Name;
                        cart2.ItemDescription = product.Description;
                    }
                }

                return(PartialView("_shopCart", cart2));
            }
        }
Ejemplo n.º 15
0
 public CartVM GetOrer()
 {
     using (var db = new ProjectWebEntities())
     {
         var model = new CartVM();
         //var httpCookie = HttpContext.Current.Request.Cookies["loginPIN"];
         //if (httpCookie != null)
         //{
         //    var pin = httpCookie.Value;
         //    model.ItemMember = db.Tbl_MemberAccount.SingleOrDefault(p => p.PIN ==pin);
         //}
         model.ListProvinces = db.Tbl_Province.OrderByDescending(p => p.Type).ToList();
         model.ListDistricts = db.Tbl_District.OrderByDescending(p => p.ProId).ThenBy(p => p.DisId).ToList();
         var listProduct = new List <Tbl_Product>();
         model.TotalPrice = 0;
         for (int i = 0; i < HttpContext.Current.Request.Cookies.Count; i++)
         {
             var productCookie = HttpContext.Current.Request.Cookies[i];
             if (productCookie != null && productCookie.Name.Contains("e0jwun4lc5_"))
             {
                 var id      = Convert.ToInt32(productCookie.Value.Split('|')[0]);
                 var product = db.Tbl_Product.Find(id);
                 product.Quantity          = Convert.ToInt32(productCookie.Value.Split('|')[1]);
                 product.TotalPriceProduct = product.RealPrice * product.Quantity;
                 model.TotalPrice          = model.TotalPrice + product.TotalPriceProduct;
                 model.TotalAllPrice       = model.TotalPrice;
                 listProduct.Add(product);
             }
         }
         model.ListProducts = listProduct.OrderBy(p => p.Name).ToList();
         return(model);
     }
 }
Ejemplo n.º 16
0
        public ActionResult LoginExisting(PersonalInfoVM model)
        {
            var cmr = db.Login(model);

            if (cmr == null)
            {
                ViewBag.LoginError = true;
                model.Countries    = db.GetCountries();
                foreach (var modelValue in ModelState.Values)
                {
                    modelValue.Errors.Clear();
                }
                return(View("PersonalInfo", model));
            }
            else
            {
                Session["CustomerId"]   = cmr.CustomerId;
                Session["CustomerName"] = cmr.CustomerName;
                Session["IsBP"]         = cmr.BPId.HasValue;
                if (cmr.BPId.HasValue && Session["Cart"] != null)
                {
                    CartVM cart = (CartVM)Session["Cart"];
                    foreach (var good in cart.Products)
                    {
                        good.Price = good.Price * 0.77M;
                    }
                }
            }
            return(RedirectToAction("checkout"));
        }
Ejemplo n.º 17
0
        public ActionResult AddToCart(CartVM viewModel)
        {
            // If we are a guest on the site use cookies for the shopping cart
            if (!UserService.IsUserConnected(System.Web.HttpContext.Current.User))
            {
                // TODO: Check if product is not null (it exists)
                HttpContext.Response.SetCookie(CookieService.AddProductToCart(Request.Cookies, viewModel.ProductId, viewModel.Size, viewModel.Quantity));

                return(RedirectToAction("Index", "ShoppingCart"));
            }

            // If we are a user on the site use he database for the shopping cart
            Product product = new ProductManager().GetProductById(viewModel.ProductId);

            if (!new ShoppingCartManager().AddProductToCart(User.Identity.GetUserId(),
                                                            product, viewModel.Size,
                                                            viewModel.Quantity))
            {
                ModelState.AddModelError("", "An error has occured.");
            }


            if (!ModelState.IsValid)
            {
                return(View());
            }

            return(RedirectToAction("Index", "ShoppingCart"));
        }
Ejemplo n.º 18
0
        // GET: Carts/Edit/5
        public async Task <ActionResult> Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Cart cart = await db.Carts.FindAsync(id);

            if (cart == null)
            {
                return(HttpNotFound());
            }

            CartVM cartVM = new CartVM(cart);

            cartVM.TransactionVMs = TransactionVM.Transactions(cart.Transactions);

            var list = db.UserRecords.OrderBy(u => u.HDBUserName).ToList();

            cartVM.Buyers    = new SelectList(list.Where(u => (u.UserType & UserRecord.UserTypes.Buyer) == UserRecord.UserTypes.Buyer), "Id", "HDBUserName");
            cartVM.Sellers   = new SelectList(list.Where(u => (u.UserType & UserRecord.UserTypes.Seller) == UserRecord.UserTypes.Seller), "Id", "HDBUserName");
            ViewBag.BuyerId  = cartVM.Buyers;
            ViewBag.SellerId = cartVM.Sellers;

            Session.Remove("Transactions");
            Session.Add("Transactions", cartVM.TransactionVMs);

            return(View(cartVM));
        }
        //Get: cart/DecrementProduct
        public JsonResult DecrementProduct(int productId)
        {
            //inicijalizovati cart listu
            List <CartVM> listCart = Session["cart"] as List <CartVM>;

            using (ShoppingCartDB db = new ShoppingCartDB())
            {
                //pronaci cartVm koristeci productId
                CartVM model = listCart.FirstOrDefault(x => x.ProductId == productId);
                //dekrementovati kolicinu
                if (model.Quantity > 1)
                {
                    model.Quantity--;
                }
                else
                {
                    model.Quantity = 0;
                    listCart.Remove(model);
                }

                //sacuvati quantity i price
                var resault = new { quantity = model.Quantity, price = model.Price };
                //vratiti json sa podacima
                return(Json(resault, JsonRequestBehavior.AllowGet));
            }
        }
Ejemplo n.º 20
0
        public void addToCart(CartVM cart)
        {
            var cartItem = db.LineItems.FirstOrDefault(c => c.Code == cart.cartID && c.ElementCode == cart.ElementCode);
            VoucherExtensionRestaurant ve = new VoucherExtensionRestaurant();

            if (cartItem == null)
            {
                cartItem = new LineItem
                {
                    Code        = cart.cartID,
                    ElementCode = cart.ElementCode,
                    UnitAmount  = cart.UnitAmount,
                    Quantity    = cart.Quantity,
                    TotalAmount = cart.TotalAmount,
                    TaxAmount   = 0,
                    TaxType     = null,
                    Remark      = null,
                    Cost        = cart.PriceValue * cart.Quantity,
                    VoucherCode = null
                };
                db.LineItems.Add(cartItem);
            }
            else
            {
                cartItem.Quantity++;
            }
            db.SaveChangesAsync();
        }
Ejemplo n.º 21
0
        public ActionResult OrderList()
        {
            int userId = (int)Session[CDictionary.SK_LOGINED_USER_ID];

            var OList = db.OrderList.Where(o => o.cId == userId && o.oStatus == 0);


            var orders = new List <orderDetail>();

            foreach (var item in OList)
            {
                orders.Add(new orderDetail
                {
                    oId          = item.oId,
                    pId          = item.pId,
                    productImg   = item.Product.pImage,
                    orderQty     = (int)item.oQty,
                    productPrice = (decimal)item.Product.pPrice,
                    productName  = item.Product.pName,
                    TP           = (decimal)((decimal)item.oQty * item.Product.pPrice),
                });
            }
            ViewBag.total = (orders.Sum(x => x.TP)).ToString("#.##");
            ViewBag.tax   = (orders.Sum(x => x.TP) * (decimal)0.12).ToString("#.##");
            Session[CDictionary.TK_Cart_TOTALPRICE] = (orders.Sum(x => x.TP) * (decimal)1.12).ToString("#.##");

            var vm = new CartVM
            {
                orderDetails = orders,
                cId          = userId,
            };


            return(View(vm));
        }
Ejemplo n.º 22
0
        //GET: /cart/DecrementProduct
        public ActionResult DecrementProduct(int productId)
        {
            //announc list cart
            List <CartVM> cart = Session["cart"] as List <CartVM>;

            using (Db db = new Db())
            {
                //get model CartVM from list
                CartVM model = cart.FirstOrDefault(x => x.ProductId == productId);

                //reduce count
                if (model.Quantity > 1)
                {
                    model.Quantity--;
                }
                else
                {
                    model.Quantity = 0;
                    cart.Remove(model);
                }

                //save required data
                var result = new { qty = model.Quantity, price = model.Price };

                //return JSON answer with data
                return(Json(result, JsonRequestBehavior.AllowGet));
            }
        }
Ejemplo n.º 23
0
        public ActionResult CartPartial()
        {
            // inicjalizacja CartVM
            CartVM model = new CartVM();

            // inicjalizacja ilosc i cena
            int     qty   = 0;
            decimal price = 0;

            // sprawdzamy czy mamy dane koszyka zapisane w sesii
            if (Session["cart"] != null)
            {
                // pobieranie wartosci z sesii
                var list = (List <CartVM>)Session["cart"];

                foreach (var item in list)
                {
                    qty   += item.Quantity;
                    price += item.Quantity * item.Price;
                }

                model.Quantity = qty;
                model.Price    = price;
            }
            else
            {
                // ustawiamy ilosc i cena na 0
                qty   = 0;
                price = 0m;
            }

            return(PartialView(model));
        }
Ejemplo n.º 24
0
        public ActionResult CartPartial()
        {
            //announce model CartVM
            CartVM model = new CartVM();

            //announce var quantity
            int qty = 0;

            //announce var price
            decimal price = 0m;

            //check session of busket
            if (Session["cart"] != null)
            {
                //get total quantity products and price
                var list = (List <CartVM>)Session["cart"];

                foreach (var item in list)
                {
                    qty   += item.Quantity;
                    price += item.Quantity * item.Price;
                }

                model.Quantity = qty;
                model.Price    = price;
            }
            else
            {
                //or install quantity and price in 0
                model.Quantity = 0;
                model.Price    = 0m;
            }
            //return part view with model
            return(PartialView("_CartPartial", model));
        }
Ejemplo n.º 25
0
        // 22
        //GET /cart/DecrementProduct
        public ActionResult DecrementProduct(int productId)
        {
            // Объявляем List cart
            List <CartVM> cart = Session["cart"] as List <CartVM>;

            using (Db db = new Db())
            {
                // получаем модель CartVM из листа
                CartVM model = cart.FirstOrDefault(x => x.ProductId == productId);

                // Отнимаем количество
                if (model.Quantity > 1)
                {
                    model.Quantity--;
                }
                else
                {
                    model.Quantity = 0;
                    cart.Remove(model);
                }

                // сохраняем необходимые еданные
                var result = new { qty = model.Quantity, price = model.Price };

                // Возвращаем JSON ответ с данными
                return(Json(result, JsonRequestBehavior.AllowGet));
            }
        }
Ejemplo n.º 26
0
        public IActionResult Payment(ShoppingCartVM shoppingCartVM)
        {
            string      userId  = User.FindFirst(ClaimTypes.NameIdentifier).Value;
            AspNetUsers userNow = usersService.GetUserById(userId);

            if (!userNow.EmailConfirmed)
            {
                ModelState.AddModelError("error", "U moet eerst uw email bevestigen.");
                return(View("Index", shoppingCartVM));
            }
            else
            {
                for (int i = 0; i < shoppingCartVM.ShoppingCart.Count; i++)
                {
                    CartVM cart = shoppingCartVM.ShoppingCart[i];

                    shoppingCartVM.ShoppingCart[i].WedstrijdId    = cart.WedstrijdId;
                    shoppingCartVM.ShoppingCart[i].ThuisClubId    = cart.ThuisClubId;
                    shoppingCartVM.ShoppingCart[i].ThuisClubNaam  = cart.ThuisClubNaam;
                    shoppingCartVM.ShoppingCart[i].UitCLubNaam    = cart.UitCLubNaam;
                    shoppingCartVM.ShoppingCart[i].StadiumNaam    = cart.StadiumNaam;
                    shoppingCartVM.ShoppingCart[i].VakNaam        = cart.VakNaam;
                    shoppingCartVM.ShoppingCart[i].WedstrijdDatum = cart.WedstrijdDatum;
                    shoppingCartVM.ShoppingCart[i].Prijs          = cart.Prijs;
                    shoppingCartVM.ShoppingCart[i].Aantal         = cart.Aantal;
                }
            }

            return(View());
        }
Ejemplo n.º 27
0
        public void RemoveProduct(int productId)
        {
            List <CartVM> lstcartVM = Session["cart"] as List <CartVM> ?? new List <CartVM>();
            CartVM        cartvm    = lstcartVM.FirstOrDefault(x => x.ProductId == productId);

            lstcartVM.Remove(cartvm);
        }
Ejemplo n.º 28
0
        public ActionResult IncrementProductQuantity(CartVM viewModel)
        {
            List <ShoppingCartProduct> scps = new List <ShoppingCartProduct>();
            int qty = viewModel.Quantity; // this is to pass by reference to have the variable at return time

            // If we are a guest on the site use cookies for the shopping cart
            if (!UserService.IsUserConnected(System.Web.HttpContext.Current.User))
            {
                HttpCookie cookie = CookieService.Increment(Request.Cookies, viewModel.ProductId,
                                                            viewModel.Size, ref qty);
                HttpContext.Response.SetCookie(cookie);

                scps = CookieService.GetShoppingCartProducts(cookie);
            }
            else // We are connected with a user account
            {
                ShoppingCartManager shoppingCartManager = new ShoppingCartManager();

                qty = shoppingCartManager.IncrementQuantity(User.Identity.GetUserId(), viewModel.ProductId, viewModel.Size);
                //TODO : Check error message and show it in view if error occured


                ShoppingCart shoppingCart = new ShoppingCartManager().GetShoppingCartByUser(User.Identity.GetUserId());

                scps = new ShoppingCartProductManager().GetShoppingCartProductByShoppingCartId(shoppingCart.ShoppingCartId);
            }

            return(Json(new { price = ShoppingCartService.GetSubTotal(scps, CookieService.GetCurrency(Request.Cookies)), qty }, JsonRequestBehavior.AllowGet));
        }
Ejemplo n.º 29
0
        public ActionResult CartPartial()
        {
            //Init CartVM
            CartVM model = new CartVM();

            int qty = 0;
            //Init price
            decimal price = 0m;

            //Check for cart session
            if (Session["cart"] != null)
            {
                //Get total qty and price
                var list = (List <CartVM>)Session["cart"];
                foreach (var item in list)
                {
                    qty   = item.Quantity;
                    price = item.Price;
                }
                model.Quantity = qty;
                model.Price    = price;
            }
            else
            {
                model.Quantity = 0;
                model.Price    = 0m;
            }
            return(PartialView(model));
        }
Ejemplo n.º 30
0
        public JsonResult DecrementProduct(int productId)
        {
            //Обьявлвяем List<CartVM>
            List <CartVM> cart = Session["cart"] as List <CartVM>;

            using (Db db = new Db())
            {
                //Получаем CartVM из List`а
                CartVM model = cart.FirstOrDefault(x => x.Id == productId);

                //Отнимаем количество
                if (model.Quantity > 1)
                {
                    model.Quantity--;
                }
                else
                {
                    model.Quantity = 0;
                    cart.Remove(model);
                }
                //Сохранеяем необходимые данные
                var result = new { qty = model.Quantity, price = model.Price };

                //Вернуть JSON ответ с данными
                return(Json(result, JsonRequestBehavior.AllowGet));
            }
        }