我想通过图像更新数据库中现有的 Product 对象,但是只有在我创建新对象时图像才能成功进入数据库。
我正在尝试以这种方式更新我的对象
[HttpPost]
public ActionResult Edit(Product product, HttpPostedFileBase image)
{
if (ModelState.IsValid)
{
if (image != null)
{
product.ImageMimeType = image.ContentType;
product.ImageData = new byte[image.ContentLength];
image.InputStream.Read(product.ImageData, 0, image.ContentLength);
}
if (product.ProductID != 0)
UpdateModel<Product>(repository.Products.FirstOrDefault(p => p.ProductID == product.ProductID));
repository.SaveProduct(product);
TempData["message"] = string.Format("{0} has been saved", product.Name);
return RedirectToAction("Index");
}
return View(product);
}
//repository.SaveProduct()
public void SaveProduct(Product product)
{
if (product.ProductID == 0)
{
context.Products.Add(product);
}
context.SaveChanges();
}
风景
@
上传新图片:input type="file"name="Image"
输入类型=“提交”值=“保存”
@Html.ActionLink("取消返回List", "Index")
}
最佳答案
我注意到您阅读了“Pro ASP.NET MVC 3 Framework”并遇到了与我相同的问题。
作者这里有错误,代码应该是(必须先引用并使用System.Data.Entity命名空间):
public void SaveProduct(Product product)
{
if (product.ProductID == 0)
{
context.Products.Add(product);
}
else
{
context.Entry(product).State = System.Data.EntityState.Modified;
}
context.SaveChanges();
}
关于c# - 在 HttpPost 之后更新模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6517081/