public async Task <IActionResult> Create(CreateImportOrderViewModel model) { try { if (ModelState.IsValid) { ImportOrder order = new ImportOrder() { PlacementDate = model.PlacementDate ?? DateTime.MinValue, WholesalerName = model.WholesalerName, WholesalerAddress = model.WholesalerAddress, WholesalerPhone = model.WholesalerPhone }; var importProductsData = TempData.Get <IList <ProductItem> >("ImportedProducts"); await _repo.Create(order, importProductsData); TempData.Put <IList <ProductItem> >("ImportedProducts", null); return(RedirectToAction(nameof(Index))); } model.ImportedOrders = TempData.Get <IList <ProductItem> >("ImportedProducts"); return(View(model)); } catch (DbUpdateException /* ex */) { return(RedirectToAction("Error", "Home", new { ErrorTitle = "Create Import Order Error", ErrorMessage = "Unable to save changes. " + "Try again, and if the problem persists " + "see your system administrator." })); //Log the error (uncomment ex variable name and write a log. } }
// GET: Employee/ImportOrders/Create public async Task <IActionResult> Create(int?idToAdd, int?idToRemove) { try { var productsQuery = _context.Products.OrderBy(p => p.Name); var importedProducts = TempData.Get <IList <ProductItem> >("ImportedProducts"); if (importedProducts != null) { if (idToRemove != null) { var item = importedProducts.FirstOrDefault(p => p.Product.ID == idToRemove); if (item != null) { if (item.Quantity > 1) { item.Quantity--; } else { importedProducts.Remove(item); } } } } if (importedProducts == null) { importedProducts = new List <ProductItem>(); } if (idToAdd != null) { var item = importedProducts.FirstOrDefault(p => p.Product.ID == idToAdd); if (item == null) { importedProducts.Add(new ProductItem { Product = await productsQuery.FirstOrDefaultAsync(p => p.ID == idToAdd), Quantity = 1 }); } else { item.Quantity++; } } TempData.Put <IList <ProductItem> >("ImportedProducts", importedProducts); var model = new CreateImportOrderViewModel { ImportedOrders = importedProducts, Products = new SelectList(await productsQuery.ToListAsync(), "ID", "Name"), PlacementDate = DateTime.Now.Date, }; return(View(model)); } catch (Exception ex) { return(RedirectToAction("Error", "Home", new { ErrorTitle = "Create Import Order Error", ErrorMessage = "Something happened while trying to create the import order:\n" + ex.Message })); } }