【发布时间】:2017-12-20 08:40:47
【问题描述】:
查看代码
@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>
}
控制器
[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);
}
我想用按钮删除图片。我该怎么做 ?我可以删除产品,但我不能删除图片。我可以删除带有 ID 的产品。我试图在互联网上做例子,但我做不到。你会做一个说明性的例子吗?
【问题讨论】:
-
只需在数据库表中创建
ImageName列并存储图像名称如product-name-123,然后使用产品ID获取ImageName并使用File.Delete删除您的图像。 -
我不明白。你能举个例子吗?谢谢。
-
我可以知道您如何将图像名称存储在文件夹中,名称如何?
-
-
编辑的代码块
标签: javascript asp.net asp.net-mvc