public ActionResult Edit(int?id, ProductsViewModel model) { var validImageTypes = new string[] { "image/gif", "image/jpeg", "image/pjpeg", "image/png" }; if (model.ImageUpload != null && !validImageTypes.Contains(model.ImageUpload.ContentType)) { ModelState.AddModelError("ImageUpload", "請選擇 GIF, JPG or PNG 圖片檔案格式。"); } if (ModelState.IsValid) { var product = db.Products.Find(id); if (product == null) { return(new HttpNotFoundResult()); } product.Name = model.Name; product.Description = model.Description; product.Category_Id = model.Category_Id; product.Price = model.Price; product.Author = model.Author; product.Publisher = model.Publisher; product.PublishDT = Convert.ToDateTime(model.PublishDT); product.IsPublic = model.IsPublic; if (model.ImageUpload != null && model.ImageUpload.ContentLength > 0) { ImageDeal imageDeal = new ImageDeal(); //上傳圖檔&壓縮圖檔處理 string imageUrl = imageDeal.Upload(model.ImageUpload); product.PhotoUrl = imageUrl; //刪除舊檔案&壓縮檔案 var deletePhotoUrl = Server.MapPath(model.PhotoUrl); imageDeal.Delete(deletePhotoUrl); } db.Entry(product).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.Category_Id = new SelectList(db.Categories, "Id", "Name", model.Category_Id); return(View(model)); }
public ActionResult DeleteConfirmed(int id) { Products products = db.Products.Find(id); db.Products.Remove(products); db.SaveChanges(); //刪除舊檔案 //刪除舊檔案&壓縮檔案 var deletePhotoUrl = Server.MapPath(products.PhotoUrl); ImageDeal imageDeal = new ImageDeal(); imageDeal.Delete(deletePhotoUrl); return(RedirectToAction("Index")); }