public async Task <IActionResult> GetProducts(long id) { Console.WriteLine(id); var cacheEntryOptions = new MemoryCacheEntryOptions() .SetSlidingExpiration(TimeSpan.FromMinutes(10)); Dictionary <Product, int> cart; string key = "cart" + id.ToString(); if (!_cache.TryGetValue(key, out cart)) { cart = new Dictionary <Product, int>(); _cache.Set(key, cart, cacheEntryOptions); } string keymsg = "msg" + id.ToString(); string msg; if (!_cache.TryGetValue(keymsg, out msg)) { msg = ""; _cache.Set(keymsg, "", cacheEntryOptions); } ProdListVM vm = new ProdListVM(); vm.prodList = await db.Products.ToListAsync(); vm.prodList = vm.prodList.OrderBy(p => p.Name).ToList(); vm.clientID = id; vm.cart = cart; vm.message = msg; return(View(vm)); }
public IActionResult Cart(long id) { try { var cacheEntryOptions = new MemoryCacheEntryOptions() .SetSlidingExpiration(TimeSpan.FromMinutes(10)); Dictionary <Product, int> cart; string key = "cart" + id.ToString(); if (!_cache.TryGetValue(key, out cart)) { cart = new Dictionary <Product, int>(); _cache.Set(key, cart, cacheEntryOptions); } ProdListVM vm = new ProdListVM(); vm.clientID = id; vm.cart = cart; return(View(vm)); } catch (Exception e) { return(Content(e.Message)); } }
public async Task <IActionResult> AddToCart(ProdListVM vm) { try { var cacheEntryOptions = new MemoryCacheEntryOptions() .SetSlidingExpiration(TimeSpan.FromMinutes(10)); Dictionary <Product, int> cart; string key = "cart" + vm.clientID.ToString(); if (!_cache.TryGetValue(key, out cart)) { cart = new Dictionary <Product, int>(); _cache.Set(key, cart, cacheEntryOptions); } string keymsg = "msg" + vm.clientID.ToString(); vm.prodList = await db.Products.ToListAsync(); vm.cart = cart; Product prod = vm.prodList.First(p => p.ID == vm.prodID); Product keyProd = new Product(); List <Product> keyList = new List <Product>(cart.Keys); bool validate = true; keyList.ForEach(p => { if (p.ID == prod.ID) { validate = false; keyProd = p; } }); if (validate) { if (vm.amount <= prod.Stock) { _cache.Set(keymsg, "Se ha añadido el producto al carrito", cacheEntryOptions); vm.cart.Add(prod, vm.amount); } else { _cache.Set(keymsg, "La cantidad ingresada supera la disponibilidad", cacheEntryOptions); } } else { if (vm.cart[keyProd] + vm.amount <= prod.Stock) { vm.cart[keyProd] += vm.amount; _cache.Set(keymsg, "Se ha añadido el producto al carrito", cacheEntryOptions); } else { _cache.Set(keymsg, "La cantidad ingresada supera la disponibilidad", cacheEntryOptions); } } _cache.Set(key, cart, cacheEntryOptions); return(RedirectToAction("GetProducts", new { id = vm.clientID })); } catch (Exception e) { return(Content(e.Message)); } }