public ActionResult Create(HttpPostedFileBase newImage, Product product, String submitButton) { switch (submitButton) { case "Add Picture": AddPicture(newImage, product); break; case "Create": if (ModelState.IsValid) { product.EditedBy = product.CreatedBy = (Guid) Membership.GetUser().ProviderUserKey; _db.Products.Add(product); foreach (Image a in product.Images) { a.Product = product; _db.Images.Add(a); } _db.SaveChanges(); return RedirectToAction("RedirectedBack", "Products"); } break; default: RemovePicture(product, submitButton); break; } PrepareSelectLists(); return View(product); }
private static void AddPicture(HttpPostedFileBase newImage, Product product) { if (newImage != null) { String filePath = Guid.NewGuid() + Path.GetExtension(newImage.FileName); var newImg = new Image { ImageId = -1, Path = filePath }; newImage.SaveAs(newImg.FullPath); product.Images.Add(newImg); } }
private static void RemovePicture(Product product, string submitButton) { string path = submitButton.Substring(7); //remove "delete:" Image removedImage = product.Images.SingleOrDefault(img => img.Path == path); if (removedImage != null) { if (removedImage.ImageId < 1) System.IO.File.Delete(removedImage.FullPath); product.Images.Remove(removedImage); } }
public ActionResult Edit(HttpPostedFileBase newImage, Product product, String submitButton) { switch (submitButton) { case "Add Picture": AddPicture(newImage, product); break; case "Save": if (ModelState.IsValid) { product.EditedBy = (Guid) Membership.GetUser().ProviderUserKey; ICollection<Image> newImages = product.Images.ToList(); Dictionary<String, Image> oldImages = _db.Images.Where(img => img.ProductId == product.ProductId).ToDictionary(image => image.Path); foreach (Image a in newImages) { if (oldImages.ContainsKey(a.Path)) { oldImages.Remove(a.Path); product.Images.Remove(a); } else { a.Product = product; _db.Images.Add(a); } } foreach (Image a in oldImages.Values) { System.IO.File.Delete(a.FullPath); _db.Images.Remove(a); } _db.Entry(product).State = EntityState.Modified; _db.SaveChanges(); return RedirectToAction("RedirectedBack", "Products"); } break; default: RemovePicture(product, submitButton); break; } PrepareSelectLists(product.CategoryId, product.ProducerId); return View(product); }