public ActionResult Create(CustomerVM customers) { var file = new CustomPostedFile(customers.Files, customers.FileName); var path = Path.Combine(Server.MapPath("~/images/"), file.FileName); customers.ImageUrl = "~/images/" + file.FileName; var newCustomer = new Customer { Country = customers.Country, ImageUrl = customers.ImageUrl, Name = customers.Name }; _db.Customers.Add(newCustomer); var added = _db.SaveChanges(); if (added <= 0) { return(RedirectToAction($"Index")); } file.SaveAs(path); ViewBag.message = "Image added"; ModelState.Clear(); return(RedirectToAction($"Index")); }
public ActionResult Edit(CustomerVM customers) { if (!ModelState.IsValid) { RedirectToAction("Edit"); } var model = _db.Customers.Find(customers.CustomerID); if (customers.Files != null) { var file = new CustomPostedFile(customers.Files, customers.FileName); var path = Path.Combine(Server.MapPath("~/images/"), file.FileName); customers.ImageUrl = "~/images/" + file.FileName; if (model != null) { model.Country = customers.Country; model.Name = customers.Name; model.ImageUrl = customers.ImageUrl; _db.Entry(model).State = EntityState.Modified; } var added = _db.SaveChanges(); var oldImage = Request.MapPath(Session["ImageUrl"].ToString()); if (added <= 0) { return(RedirectToAction("Index")); } var imageExists = System.IO.File.Exists(oldImage); if (imageExists) { System.IO.File.Delete(oldImage); } file.SaveAs(path); } else { if (model != null) { model.Country = customers.Country; model.Name = customers.Name; _db.Entry(model).State = EntityState.Modified; } _db.SaveChanges(); } return(RedirectToAction("Index")); }