下面是一些基本设置,应该适合您。
操作方法:
public ActionResult Index()
{
//Adding some dummy product data for example, Usually you will get real details from DB.
List<Product> products = new List<Product>();
Product product1 = new Product()
{
Id = 1,
Name = "Bint Beef",
Description = "Product Bint Beef",
ImageName = "bintbeef-1"
};
Product product2 = new Product()
{
Id = 2,
Name = "Bint Beef 2",
Description = "Product Bint Beef 2",
ImageName = "bintbeef-2"
};
products.Add(product1);
products.Add(product2);
return View(products);
}
[HttpPost]
public ActionResult DeleteProductImage(int productID)
{
try
{
string file_name = Convert.ToString(productID);
//Here you can instead use `ImageName` property to fetch the name from db based
on product id and then delete image
string path = Server.MapPath("~/Content/Images/" + file_name + ".jpg");
FileInfo file = new FileInfo(path);
if (file.Exists)//check file exsit or not
{
file.Delete();
}
return Json(new { status = true }, JsonRequestBehavior.AllowGet);
}
catch
{
return Json(new { status = false }, JsonRequestBehavior.AllowGet);
}
}
索引视图
@model IEnumerable<DemoMvc.Models.Product>
<h2>Product List</h2>
<table class="table">
<tr>
<th>
Product Id
</th>
<th>
Name
</th>
<th>
Image Name
</th>
</tr>
@foreach (var item in Model)
{
<tr>
<th>
@item.Id
</th>
<td>
@item.Name
</td>
<td>
@item.ImageName
</td>
<td>
@using (Html.BeginForm("DeleteProductImage", "Home"))
{
<input name="productID" type="hidden" value="@item.Id" />
<button type="submit">Delete Image</button>
}
</td>
</tr>
}
</table>
Reference
.