public IndexModel(ApplicationDbContext context, IHttpContextAccessor httpContextAccessor, ShoppingCart shoppingCart) { _context = context; _httpContextAccessor = httpContextAccessor; ShoppingCart = shoppingCart; ListOfShipsInCart = shoppingCart.GetShoppingList(); if (ListOfShipsInCart != null && ListOfShipsInCart.Count > 0) { foreach (var item in ListOfShipsInCart) { if (item.Model == "You haven't added anything yet." && ListOfShipsInCart.Count > 1) { ListOfShipsInCart.Remove(item); } TotalCost = item.Price + TotalCost; } } else { ListOfShipsInCart = new List <Ship>() { new Ship { Model = "You haven't added anything yet.", } }; } }
public async Task <IActionResult> OnPostFinalizeOrder() { string userId; IdentityUser databaseUser; try { userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value; databaseUser = _context.Users.Single(user => user.Id == userId); } catch { CheckOutFailed = true; return(Page()); } var order = new Order { User = databaseUser, DateOfPurchase = DateTime.Today, }; var shipOrders = new List <ShipOrder>(); foreach (var item in ListOfShipsInCart) { if (shipOrders.Any(so => so.ShipId == item.Id)) { continue; } shipOrders.Add(new ShipOrder { Ship = _context.Ship.Attach(item).Entity, ShipId = item.Id, Order = order, OrderId = order.Id, Count = ListOfShipsInCart.Where(s => s.Id == item.Id).ToList().Count(), }); } try { if (ModelState.IsValid) { foreach (var item in shipOrders) { await _context.ShipOrder.AddAsync(item); } } } catch (Exception e) { Console.WriteLine(e.Message); } await _context.SaveChangesAsync(); ShoppingCart.OrderedShips.AddRange(shipOrders); // Should relocate this v //await OnPostClearCart(); return(RedirectToPage("Summary")); }