我想通過圖像更新數據庫中現有的產品對象,但只有當我創建新對象時,圖像纔會成功轉到數據庫。在HttpPost後更新模型
我試圖更新我的對象這樣
[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();
}
觀 @ Upload new image: input type="file" name="Image" input type="submit" value="Save" @Html.ActionLink("Cancel and return to List", "Index") }
他爲什麼要改變他決定的方式,如果它是一個新對象? – jgauffin
我沒有說「他應該」,但是表示「EditMode」的布爾變量更健壯。 –
爲什麼它更健壯? ID爲0很清楚,不是嗎? – jgauffin