public ActionResult AddressAndPayment(FormCollection values) { var shoppCart = ShoppingCart.GetCart(this.HttpContext); // Set up our ViewModel var viewModel = new ShoppingCartViewModel { CartItems = shoppCart.GetCartItems(), CartTotal = shoppCart.GetTotal() }; var order = new Order(); using (var dbContextTransaction = storeDB.Database.BeginTransaction()) { try { TryUpdateModel(order); order.Username = User.Identity.Name; order.OrderDate = DateTime.Now; //Save Order storeDB.Orders.Add(order); storeDB.SaveChanges(); //Process the order shoppCart.CreateOrder(order); dbContextTransaction.Commit(); return RedirectToAction("Complete", new { id = order.ID }); } catch (Exception) { dbContextTransaction.Rollback(); ModelState.AddModelError("", "There was an error while processing your order, please try again."); } } ViewBag.Cart = viewModel; return View(order); }
public int CreateOrder(Order order) { decimal orderTotal = 0; var cartItems = GetCartItems(); // Iterate over the items in the cart, // adding the order details for each foreach (var item in cartItems) { var orderDetail = new OrderDetail { ProductID = item.ProductID, OrderID = order.ID, UnitPrice = item.Price, Quantity = item.Count, Order = order, Product = item.Product }; // Set the order total of the shopping cart orderTotal += (item.Count * item.Price); storeDB.SaveChanges(); storeDB.OrderDetails.Add(orderDetail); storeDB.SaveChanges(); } // Set the order's total to the orderTotal count order.Total = orderTotal; storeDB.Entry(order).State = EntityState.Modified; // Save the order storeDB.SaveChanges(); // Empty the shopping cart EmptyCart(); // Return the OrderId as the confirmation number return order.ID; }