Check Out the Code
@using(Html.BeginForm("Edit",
"Products",
FormMethod.Post,
new {
enctype = "multipart/form-data"
})) {
@Html.AntiForgeryToken()
< div class = "form-horizontal" >
@Html.ValidationSummary(true, "", new {
@class = "text-danger"
})
@Html.HiddenFor(model => model.Id)
< div class = "form-group" >
@Html.LabelFor(model => model.Image, htmlAttributes: new {
@class = "control-label col-md-2"
}) < div class = "col-md-10" >
< img src = "@Url.Content(Model.Image)"
width = "150" / >
< /div> < /div>
}
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Product product, HttpPostedFileBase file) {
if (ModelState.IsValid) {
Product p = new Product {
Id = product.Id,
Name = product.Name,
Description = product.Description,
Image = product.Image
};
if (file != null) {
string Image = Path.Combine(Server.MapPath("~/Upload"), Path.GetFileName(file.FileName));
file.SaveAs(Image);
p.Image = "~/Upload/" + file.FileName;
}
db.Entry(p).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
} else {
return View(product);
}
}
public ActionResult Edit(int ? id) {
if (id == null) {
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Product product = db.Products.Find(id);
if (product == null) {
return HttpNotFound();
}
return View(product);
}
I would like to remove the image with a button. How do I achieve this? While I can delete products using their IDs, I'm having trouble deleting images. Although I've tried following examples from online resources, I haven't been successful. Could you provide an illustrative example for me?