Esempio n. 1
0
        public async Task <IActionResult> Index()
        {
            string tempCartId             = httpContextAccessor.HttpContext.Request.Cookies["tempCartId"];
            List <TempCartItem> tempCarts = cartServices.GetTempCartList(tempCartId);

            if (tempCarts != null)
            {
                foreach (TempCartItem item in tempCarts)
                {
                    cartServices.addToCart(UserName, item.Product.Id, item.Quantity);
                }
                await cartServices.DeleteTempCart(tempCartId);
            }
            List <CartItem>   cart      = cartServices.GetCartList(UserName);
            CartListViewModel viewModel = new CartListViewModel();

            if (cart != null)
            {
                viewModel.CartItems = cart
                                      .Select(x => new CartViewModel()
                {
                    Id           = x.Id,
                    ImageAddress = x.Product.PictureAddress,
                    Price        = x.Product.Price,
                    Quantity     = x.Quantity,
                    Title        = x.Product.Title
                }).ToList();
                viewModel.TotalPrice = cart.Sum(x => x.Quantity * x.Product.Price);
            }
            else
            {
                viewModel = new CartListViewModel()
                {
                    CartItems  = new List <CartViewModel>(),
                    TotalPrice = 0
                };
            }
            return(View(viewModel));
        }
        public IActionResult AddProductToCart(int productId, int quantity = 1)
        {
            ProductAddToOrderViewModel result;

            if (UserName == null)
            {
                //here the code for managing the un authorize customer to store cart in temp table with uniqe id and store the id in user cookie to retrive the data
                string tempCartId = httpContextAccessor.HttpContext.Request.Cookies["tempCartId"];
                if (tempCartId == null || tempCartId == "")
                {
                    Guid g = Guid.NewGuid();
                    tempCartId = g.ToString();
                    CookieOptions option = new CookieOptions();
                    option.Expires = DateTime.Now.AddDays(7);
                    Response.Cookies.Append("tempCartId", tempCartId, option);
                }
                result = cartServices.addToTempCart(tempCartId, productId, quantity);
            }
            else
            {
                result = cartServices.addToCart(UserName, productId, quantity);
            }
            return(Json(result));
        }