public ActionResult EditProduct(ProductViewModel model, HttpPostedFileBase file) { ProductViewModel fetchedData = null; var config = new MapperConfiguration(cfg => { cfg.CreateMap <ProductViewModel, Product>(); }); IMapper mapper = config.CreateMapper(); Product sensitiveData = mapper.Map <ProductViewModel, Product>(fetchedData); // Get product id int id = sensitiveData.Id; // Populate categories select list and gallery images sensitiveData.Categories = new SelectList(shopBL.SelectListItem(), "Id", "Name"); sensitiveData.GalleryImages = Directory.EnumerateFiles(Server.MapPath("~/Images/Uploads/Products/" + id + "/Gallery/Thumbs")) .Select(fn => Path.GetFileName(fn)); // Check model state if (!ModelState.IsValid) { return(View(model)); } // Make sure product name is unique if (shopBL.CheckProduct(sensitiveData, id)) { ModelState.AddModelError("", "That product name is taken!"); return(View(model)); } // Update product Product product = shopBL.UpdateProduct(id, sensitiveData); product.Name = model.Name; product.Slug = model.Name.Replace(" ", "-").ToLower(); product.Description = model.Description; product.Price = model.Price; product.CatagoryId = model.CatagoryId; product.ImageName = model.ImageName; // Set TempData message TempData["SM"] = "You have edited the product!"; #region Image Upload // Check for file upload if (file != null && file.ContentLength > 0) { // Get extension string ext = file.ContentType.ToLower(); // Verify extension if (ext != "image/jpg" && ext != "image/jpeg" && ext != "image/pjpeg" && ext != "image/gif" && ext != "image/x-png" && ext != "image/png") { ModelState.AddModelError("", "The image was not uploaded - wrong image extension."); return(View(model)); } // Set uplpad directory paths var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\"))); var pathString1 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()); var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs"); // Delete files from directories DirectoryInfo di1 = new DirectoryInfo(pathString1); DirectoryInfo di2 = new DirectoryInfo(pathString2); foreach (FileInfo file2 in di1.GetFiles()) { file2.Delete(); } foreach (FileInfo file3 in di2.GetFiles()) { file3.Delete(); } // Save image name string imageName = file.FileName; Product product1 = shopBL.FindProduct(id); product1.ImageName = imageName; // Save original and thumb images var path = string.Format("{0}\\{1}", pathString1, imageName); var path2 = string.Format("{0}\\{1}", pathString2, imageName); file.SaveAs(path); WebImage img = new WebImage(file.InputStream); img.Resize(192, 250); img.Save(path2); } #endregion // Redirect return(RedirectToAction("EditProduct")); }