我正在阅读 Apress 的 Pro ASP.NET MVC 3 Framework。我正在遵循上传和显示图像的示例。问题是它在将图像上传到产品时工作正常,但如果我稍后想编辑描述,然后保存产品,图像就会消失。我知道问题是在保存产品时我没有传递图像数据,因为图像上传是空的,并且 context.SaveChanges() 保存了每个数据字段,包括空的图像数据字段。
我被困住了,如果有人可以帮助我,我将不胜感激!
这是编辑页面的一部分:
<label>Image</label>
if (Model.ImageData == null)
{
@:Null
}
else
{
<img id="imageFile" runat="server" src="@Url.Action("GetImage", "Product", new { Model.Name })" />
}
<label>Upload image:</label>
<input type="file" name="Image" runat="server" />
更新时:
public ActionResult Edit(Product product, HttpPostedFileBase image)
{
if (ModelState.IsValid)
{
if (image != null && image.ContentLength > 0)
{
product.ImageMimeType = image.ContentType;
product.ImageData = new byte[image.ContentLength];
image.InputStream.Read(product.ImageData, 0, image.ContentLength);
}
repository.SaveProduct(product);
TempData["message"] = string.Format("{0} har sparats", product.Name);
return RedirectToAction("Index");
}
else
{
return View(product);
}
}
保存产品:
public void SaveProduct(Product product)
{
if (product.ProductID == 0)
{
context.Products.Add(product);
}
else
{
context.Entry(product).State = EntityState.Modified;
}
int result = context.SaveChanges();
}