public async Task <IActionResult> DeleteProductConfirmed(int?Id) { // Get product so we can get the image path Product product = await webAPI.GetOneAsync <Product>(ApiURL.PRODUCTS + Id); // Send to API and delete product var token = await webAPIToken.New(); var apiResonse = await webAPI.DeleteAsync(ApiURL.PRODUCTS + Id, token); ProductImage deleteImage = new ProductImage(environment.WebRootPath); deleteImage.DeleteImage(product.Photo); if (product != null) { TempData["Deleted"] = $"{product.Name} är borttagen!"; return(RedirectToAction("AllProducts", "Product")); } else { return(Content("Det sket sig.")); } }
public async Task <ActionResult> EditProduct(IFormFile file, [Bind] AllProductsViewModel model) { try { // Get product by id from API var productInDB = await webAPI.GetOneAsync <AllProductsViewModel>(ApiURL.PRODUCTS + model.Id); if (ModelState.IsValid) { if (!IsUploadedFileImage(file)) { ModelState.AddModelError("Photo", "Filen är ogiltig!"); TempData["Errors"] = "Filen är ogiltig!"; model.Categories = await webAPI.GetAllAsync <Category>(ApiURL.CATEGORIES); model.Brands = await webAPI.GetAllAsync <Brand>(ApiURL.BRANDS); return(View(model)); } Product editproduct = new Product() { Id = model.Id, Name = model.Name, Price = Convert.ToDecimal(model.Price.ToString().Replace('.', ',')), Quantity = model.Quantity, CategoryId = model.CategoryId, BrandId = model.BrandId, Description = model.Description, Photo = model.Photo, FullDescription = model.FullDescription, Specification = model.Specification, Discount = Convert.ToSingle(model.Discount.ToString().Replace('.', ',')), ActiveProduct = model.ActiveProduct }; // Set category folder name var folderName = await GetCategoryName(model.CategoryId); // Update image if (file != null) { // Remove old image and store new image ProductImage productImage = new ProductImage(environment.WebRootPath, folderName, file); productImage.DeleteImage(editproduct.Photo); editproduct.Photo = productImage.StoreImage(editproduct.Id); } // If category was changed, move existing product photo to selected folder else if (productInDB.CategoryId != model.CategoryId) { // Move image to new location ProductImage productImage = new ProductImage(environment.WebRootPath, folderName, editproduct.Photo); editproduct.Photo = productImage.MoveImage(); } // Send to API and update product var token = await webAPIToken.New(); var apiResonse = await webAPI.UpdateAsync(editproduct, ApiURL.PRODUCTS + editproduct.Id, token); } else { // TODO: Separate this to its own method? model.Categories = await webAPI.GetAllAsync <Category>(ApiURL.CATEGORIES); model.Brands = await webAPI.GetAllAsync <Brand>(ApiURL.BRANDS); return(View(model)); } TempData["EditSuccesmsg"] = $"{model.Name} har uppdaterats!"; return(RedirectToAction("AllProducts", "Product")); } catch { TempData["EditDatabase error"] = "Oops! Något gick fel. Försök igen eller kontakta support om problemet kvarstår."; return(RedirectToAction("EditProduct", "Product")); } }