public IActionResult AddToCart(int productId, AddToCartViewModel item) { //var foo = await TryUpdateModelAsync(item); if (!ModelState.IsValid) { return(View(item)); } //Do work //Recheck model //var isValid = TryValidateModel(item); try { var mapper = _config.CreateMapper(); var cartRecord = mapper.Map <ShoppingCartRecord>(item); cartRecord.DateCreated = DateTime.Now; _shoppingCartRepo.Context.CustomerId = ViewBag.CustomerId; _shoppingCartRepo.Add(cartRecord); } catch (Exception) { ModelState.AddModelError(string.Empty, "There was an error adding the item to the cart."); return(View(item)); } return(RedirectToAction(nameof(CartController.Index))); }
public IActionResult RemoveItemFromCart(int?product, AddToCartViewModel model) { product = HttpContext.Session.GetInt32("ProductId"); List <AddToCartViewModel> addToCartList = HttpContext.Session.Get <List <AddToCartViewModel> >("CartItem"); int itemInCart = 0; var valu = HttpContext.Session.GetInt32("itemCount"); if (valu != null) { itemInCart = valu.Value; } if (addToCartList.Where(x => x.ProductId == product).ToList().Count > 0) { AddToCartViewModel cart = addToCartList.FirstOrDefault(x => x.ProductId == product); if (cart != null) { addToCartList.Remove(cart); } HttpContext.Session.Set <List <AddToCartViewModel> >("CartItem", addToCartList); itemInCart = HttpContext.Session.Get <List <AddToCartViewModel> >("CartItem").Count; } HttpContext.Session.SetInt32("itemCount", itemInCart); return(RedirectToAction("Index")); }
public IActionResult AddToCart(int productId) { var cart = new AddToCartViewModel(); cart.ProductId = productId; return(View(cart)); }
void AddItemToCart(AddToCartViewModel viewModel, string cartData, HttpCookie cookie) { var cart = cartSerializer.Deserialize(cartData); cart = cartRepository.AddItem(cart, viewModel.ProductId, viewModel.Quantity); cookie.Value = cartSerializer.Serialize(cart); }
public IActionResult AddItemToCart(AddToCartViewModel addToCartViewModel) { _cartService.AddToCart(addToCartViewModel); if (AllCategoriesAndBrands(addToCartViewModel)) { return(RedirectToAction("Index", "Catalog", new { categorySlug = "", brandSlug = "", page = addToCartViewModel.Page == "1" ? null : addToCartViewModel.Page })); } else { return(RedirectToAction("Index", "Catalog", new { categorySlug = addToCartViewModel.CategorySlug, brandSlug = addToCartViewModel.BrandSlug, page = addToCartViewModel.Page == "1" ? null : addToCartViewModel.Page })); } }
public IActionResult Index(IEnumerable <OrderDetailsViewModel> product) { List <AddToCartViewModel> addToCartList = HttpContext.Session.Get <List <AddToCartViewModel> >("CartItem"); List <AddToCartViewModel> modelCart = new List <AddToCartViewModel>(); int itemInCart = 0; double estimatePrice = 0; double totalPrice = 0; var valu = HttpContext.Session.GetInt32("itemCount"); if (valu != null) { itemInCart = valu.Value; } HttpContext.Session.Set <List <AddToCartViewModel> >("CartItem", modelCart); foreach (var item in product) { AddToCartViewModel cart = new AddToCartViewModel(); cart.ProductId = item.ProductId; cart.FinalPrice = item.FinalPrice; cart.ProductName = item.ProductName; cart.Quantity = item.Quantity; estimatePrice = item.Quantity * item.FinalPrice; totalPrice = totalPrice + estimatePrice; modelCart.Add(cart); } HttpContext.Session.Set <List <AddToCartViewModel> >("CartItem", modelCart); itemInCart = HttpContext.Session.Get <List <AddToCartViewModel> >("CartItem").Count; HttpContext.Session.SetInt32("itemCount", itemInCart); HttpContext.Session.SetInt32("TotalPrice", Convert.ToInt32(totalPrice)); return(RedirectToAction(nameof(NewOrder))); }
public ActionResult AddBook(int id, AddToCartViewModel model) { var book = db.Books.Where(q => q.DeletedAt == null && q.Id == id).FirstOrDefault(); if (book == null) { return(NotFound()); } CartViewModel cart = GetCart(); CartItemViewModel cartItem = new CartItemViewModel() { Id = book.Id, Name = book.Name, Slug = book.Slug, Quantity = model.Quantity <= 0 ? 1 : model.Quantity, Price = book.Price, Discount = book.Discount, Image = book.DecodedImages()[0] }; cart.UpdateItem(cartItem); if (cart.GetItem(book.Id).Quantity > book.Quantity) { return(BadRequest("NOT_ENOUGH_BOOK")); } SaveCart(cart); return(Success(cart)); }
public void AddToCart(AddToCartViewModel addToCartViewModel) { var cart = GetCart(); if (cart != null) { var existingCartIem = _cartItemRepository.FindCartItemByCartId(cart.Id) .FirstOrDefault(c => c.ProductId == addToCartViewModel.ProductId); if (existingCartIem != null) { existingCartIem.Quantity++; _cartItemRepository.UpdateCartItem(existingCartIem); } else { var product = _productRepository.FindProductById(addToCartViewModel.ProductId); if (product != null) { var cartItem = new CartItem { CartId = cart.Id, Cart = cart, ProductId = addToCartViewModel.ProductId, Product = product, Quantity = 1 }; _cartItemRepository.SaveCartItem(cartItem); } } } else { var product = _productRepository.FindProductById(addToCartViewModel.ProductId); if (product != null) { var newCart = new Cart { UniqueCartId = UniqueCartId(), CartStatus = CartStatus.Open }; _cartRepository.SaveCart(newCart); var cartItem = new CartItem { CartId = newCart.Id, Cart = newCart, ProductId = addToCartViewModel.ProductId, Product = product, Quantity = 1 }; _cartItemRepository.SaveCartItem(cartItem); } } }
public static AddToCartDto ToDto(this AddToCartViewModel source, string userId) { return(new AddToCartDto { ProductId = source.ProductId, UserId = userId }); }
public IActionResult AddToCart(AddToCartViewModel model) { var qty = model.Qty; var list = _productrepository.AddToCart(model, model.ProductId); return(View(model)); }
public IHttpActionResult Add(AddToCartViewModel model) { if (model?.Quantity >= 0) { Cart.Add(model.ArticleNumber, model.Quantity, string.Empty, _routeRequestLookupInfoAccessor.RouteRequestLookupInfo.Channel.WebsiteLanguageSystemId ?? Guid.Empty); } return(Ok(_cartViewModelBuilder.Build(Cart))); }
public CartViewModel AddToCart(CartViewModel cartModel, AddToCartViewModel addToCartModel) { var cartProduct = cartModel.Products.SingleOrDefault(p => p.ProductId == addToCartModel.ProductId); var product = _productWebService.GetProductById(addToCartModel.ProductId); bool productQuantityUpdated = false; if (!_productWebService.ProductQuantityIsOk(addToCartModel.ProductId, addToCartModel.SizeId)) { return(null); } else { productQuantityUpdated = _productWebService.ReduceProductQuantity(addToCartModel.ProductId, addToCartModel.SizeId, 1); } if (!productQuantityUpdated) { return(null); } if (cartProduct == null) { //product not found in cart, add new cartModel.Products.Add(new ProductItemViewModel() { ProductId = addToCartModel.ProductId, Brand = product.Brand.BrandName, Quantity = 1, Size = product.Sizes.SingleOrDefault(p => p.Id == addToCartModel.SizeId).Size, Price = product.Price }); } else { var size = product.Sizes.SingleOrDefault(p => p.Id == addToCartModel.SizeId); if (size == null) { //product found but size not found, add new cartModel.Products.Add(new ProductItemViewModel() { ProductId = addToCartModel.ProductId, Brand = product.Brand.BrandName, Quantity = 1, Size = product.Sizes.SingleOrDefault(p => p.Id == addToCartModel.SizeId).Size, Price = product.Price }); } else if (addToCartModel.SizeId == size.Id) { cartProduct.Quantity++; } } return(cartModel); }
public ActionResult Add(AddToCartViewModel viewModel) { var cookie = Request.Cookies[CartCookieName] ?? new HttpCookie(CartCookieName); var cartData = cookie.Value ?? "[]"; AddItemToCart(viewModel, cartData, cookie); Response.SetCookie(cookie); return(RedirectToAction("Index", "Home")); }
public void AddToCart(AddToCartViewModel viewmodel, string account) { var orderrepo = new OrdersRepository(); var orderdetailrepo = new OrderDetailRepository(); var members = new MembersRepository(); var memberid = members.GetMemberIDByAccount(account); orderdetailrepo.AddToCartOrderDetail(viewmodel, orderrepo.GetCartOrderID(memberid)); }
public PartialViewResult AddToCart(int?id) { Resource resource = db.Resources.Where(x => x.IdResource == id).FirstOrDefault(); AddToCartViewModel model = new AddToCartViewModel() { Name = resource.Name }; return(PartialView(model)); }
public ActionResult AddItem(AddToCartViewModel model) { ShoppingCart cart = GetOrCreateCart(); ShoppingCartItem existingCartItem = cart.ShoppingCartItems.FirstOrDefault(i => i.ProductId == model.ProductId && i.Options == model.Options); if (existingCartItem != null) { // Add quantity to existing cart item existingCartItem.Quantity += model.Quantity ?? 1; } else { // Add item to cart var cartItem = new ShoppingCartItem { ShoppingCart = cart, ProductId = model.ProductId, Quantity = model.Quantity ?? 1, Options = model.Options }; Product product = db.Products.Find(cartItem.ProductId); if (product.Skus.Any()) { var optionsDeserialized = JsonConvert.DeserializeObject <ShoppingCartItemOptionViewModel[]>(model.Options); int[] optionIds = optionsDeserialized.Select(o => o.id).ToArray(); //List<Option> options = db.Options.Where(o => optionIds.Contains(o.Id)).ToList(); var skus = productSkuService.Find(product.Id, optionIds); if (skus.Any()) { cartItem.ProductSku = skus.First(); } } if (cartItem.ProductSku != null && cartItem.ProductSku.Price.HasValue) { cartItem.ItemPrice = cartItem.ProductSku.Price.Value; } else { cartItem.ItemPrice = product.SalePrice ?? product.Price; } db.ShoppingCartItems.Add(cartItem); } db.SaveChanges(); return(RedirectToAction("Index").WithSuccess("Item added to cart!")); }
public IActionResult Index(int id) { var product = db.Products.FirstOrDefault(i => i.Id == id); var obj = new AddToCartViewModel() { Product = product }; ViewBag.ProductCount = shopCart.ProductCount(); return(View(obj)); }
public ActionResult AddItem(AddToCartViewModel model) { ShoppingCart cart = GetOrCreateCart(); ShoppingCartItem existingCartItem = cart.ShoppingCartItems.FirstOrDefault(i => i.ProductId == model.ProductId && i.Options == model.Options); if (existingCartItem != null) { // Add quantity to existing cart item existingCartItem.Quantity += model.Quantity ?? 1; } else { // Add item to cart var cartItem = new ShoppingCartItem { ShoppingCart = cart, ProductId = model.ProductId, Quantity = model.Quantity ?? 1, Options = model.Options }; Product product = db.Products.Find(cartItem.ProductId); if (product.Skus.Any()) { var optionsDeserialized = JsonConvert.DeserializeObject<ShoppingCartItemOptionViewModel[]>(model.Options); int[] optionIds = optionsDeserialized.Select(o => o.id).ToArray(); //List<Option> options = db.Options.Where(o => optionIds.Contains(o.Id)).ToList(); var skus = productSkuService.Find(product.Id, optionIds); if (skus.Any()) { cartItem.ProductSku = skus.First(); } } if (cartItem.ProductSku != null && cartItem.ProductSku.Price.HasValue) { cartItem.ItemPrice = cartItem.ProductSku.Price.Value; } else { cartItem.ItemPrice = product.SalePrice ?? product.Price; } db.ShoppingCartItems.Add(cartItem); } db.SaveChanges(); return RedirectToAction("Index").WithSuccess("Item added to cart!"); }
public async Task <IActionResult> Add(AddToCartViewModel model) { var cartContext = HttpContext.GetCartContext(); await cartContext.AddOrUpdateItemAsync(new AddOrUpdateCartItemArgs { ArticleNumber = model.ArticleNumber, Quantity = model.Quantity, }); return(Ok(_cartViewModelBuilder.Build(cartContext))); }
public ActionResult Details(AddToCartViewModel viewModel) { if (ModelState.IsValid) { for (int i = 0; i < viewModel.Quantity; i++) { base.AddToSelectedOrderItems(viewModel.CD.Id); } return(RedirectToAction("Index")); } return(View(viewModel)); }
public IActionResult Add(AddToCartViewModel model) { var serviceResult = _userService.AddToCart(model.ToDto(UserId)); if (serviceResult.IsSuccess) { var carts = _userService.GetCarts(UserId).ToViewModel(); var cartServiceResult = serviceResult.AddData <List <CartViewModel> >(carts); return(Json(cartServiceResult)); } return(Json(serviceResult)); }
public ActionResult <ApiResultDto <bool> > AddToCart([FromBody] AddToCartViewModel model) { var isAdded = _shoppingCartService.AddToCart(model.CustomerId, model.ProductId, model.Quantity); var result = new ApiResultDto <bool> { Data = isAdded, Status = isAdded ? ResultStatusEnum.Success : ResultStatusEnum.Error, Message = isAdded ? "Item has been added to cart successfully." : "Has no stock." }; return(result); }
public ActionResult AddToCart() { var cart = _context.Carts.ToList(); var customer = _context.Customers.ToList(); var viewModel = new AddToCartViewModel { Cart = cart, Customer = customer }; return(View(viewModel)); }
/// <summary> /// Adds shopping cart into the database /// </summary> /// <param name="model">Model which is used to create Shopping Cart entity</param> /// <returns>Message model with error message in case of error or success message.</returns> public async Task <MessageViewModel> AddAsync(AddToCartViewModel model) { var messageViewModel = new MessageViewModel(); var userCart = await this.GetOrCreateUserCartAsync(model.UserId); var productToAdd = this.dbContext.Products.FirstOrDefault(p => p.Id == model.ProductId); if (productToAdd == null) { messageViewModel.SetError($"Продукт с ID {model.ProductId} не съществува."); return(messageViewModel); } if (userCart.ShoppingCartDetails.Any(scd => scd.ProductId == productToAdd.Id)) { var productDetails = userCart.ShoppingCartDetails.FirstOrDefault(scd => scd.ProductId == productToAdd.Id); productDetails.Quantity++; if (productToAdd.AvailableQuantity < productDetails.Quantity) { messageViewModel.SetError($"Недостатъчно количесто, в момента наличното е: {productToAdd.AvailableQuantity}."); return(messageViewModel); } this.dbContext.ShoppingCartDetails.Update(productDetails); await this.dbContext.SaveChangesAsync(); } else { if (productToAdd.AvailableQuantity < model.Quantity) { messageViewModel.SetError($"Недостатъчно количесто, в момента наличното е: {productToAdd.AvailableQuantity}."); return(messageViewModel); } ShoppingCartDetails shoppingCartDetails = new ShoppingCartDetails { ProductId = productToAdd.Id, Quantity = model.Quantity, ShoppingCartId = userCart.Id }; await this.dbContext.ShoppingCartDetails.AddAsync(shoppingCartDetails); await dbContext.SaveChangesAsync(); } messageViewModel.SetSuccess("Продуктът успешно беше добавен към вашата количка."); return(messageViewModel); }
public ActionResult SimpleProduct(AddToCartViewModel viewmodel) { var cookie = Request.Cookies[FormsAuthentication.FormsCookieName]; var ticket = FormsAuthentication.Decrypt(cookie.Value); var UserAccount = ticket.Name.Split(',')[1]; var product_service = new ProductsService(); product_service.AddToCart(viewmodel, UserAccount); var tmp = viewmodel; return(Redirect("~/orders/checkorder")); }
public IActionResult AddToCartPost(int customerId, int productId, AddToCartViewModel item) { if (!ModelState.IsValid) { return(View(item)); } try { var mapper = _config.CreateMapper(); var cartRecord = mapper.Map <ShoppingCartRecord>(item); cartRecord.DateCreated = DateTime.Now; cartRecord.CustomerId = item.CustomerId ?? 0; _shoppingCartRepo.Add(cartRecord); } catch (Exception ex) { ModelState.AddModelError(string.Empty, "There was an error adding the item to the cart."); return(View(item)); } return(RedirectToAction(nameof(CartController.Index), new { customerId })); }
public async Task <IActionResult> AddToCart(AddToCartViewModel model) { if (model.Quantity > 0) { var userId = _userManager.GetUserAsync(User).Result.Id; var dto = _mapper.Map <CartItemDto>(model); dto.UserId = userId; await _cartService.AddToCart(dto, userId); return(RedirectToAction(nameof(Index))); } return(NoContent()); }
public async Task <IActionResult> Add(int productId) { AddToCartViewModel addToCartModel = new AddToCartViewModel() { ProductId = productId, Quantity = 1, UserId = this.User.GetUserId() }; var messageViewModel = await this.shoppingCartService.AddAsync(addToCartModel); messageViewModel.SetMessage(this); return(RedirectToAction("Index")); }
public IActionResult RemoveItemFromCart(int product) { AddToCartViewModel model = new AddToCartViewModel(); List <AddToCartViewModel> addToCartList = HttpContext.Session.Get <List <AddToCartViewModel> >("CartItem"); //string name = ""; model = addToCartList.FirstOrDefault(x => x.ProductId == product); if (model != null) { HttpContext.Session.SetInt32("ProductId", product); } return(PartialView("_RemoveItemFromCart", model)); }
public void AddToCartOrderDetail(AddToCartViewModel viewmodel, int orderid) { var sql = "INSERT INTO OrderDetail(OrderID, ProductID, UnitPrice, Quantity, SizeType, Color) VALUES(@OrderID, @ProductID, @Quantity , @UnitPrice, @SizeType, @Color)"; var parameters = new DynamicParameters(); parameters.Add("@OrderID", orderid); parameters.Add("@ProductID", viewmodel.ProductID); parameters.Add("@UnitPrice", viewmodel.UnitPrice); parameters.Add("@Quantity", viewmodel.Quantity); parameters.Add("@SizeType", viewmodel.Size); parameters.Add("@Color", viewmodel.Color); using (var connection = new SqlConnection(source.connectcloud)) { connection.Query <AddToCartViewModel>(sql, parameters); } }
public async Task <IActionResult> AddToCart(int productId, AddToCartViewModel item) { if (!ModelState.IsValid) { return(View(item)); } try { await _serviceWrapper.AddToCartAsync(ViewBag.CustomerId, productId, item.Quantity); } catch (Exception) { ModelState.AddModelError(string.Empty, "There was an error adding the item to the cart."); return(View(item)); } return(RedirectToAction(nameof(CartController.Index))); }