I want to update existing Product objects in database by images, but image goes to DB successfully only when i create new objects.
I'm trying to update my object this way
[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();
}
The View
@
Upload new image: input type="file" name="Image"
input type="submit" value="Save"
@Html.ActionLink("Cancel and return to List", "Index")
}
I noticed you were read the "Pro ASP.NET MVC 3 Framework" and meet this issue same to me.
The author had a error at here, the code should be(You must reference and using the System.Data.Entity namespace at first):
public void SaveProduct(Product product)
{
if (product.ProductID == 0)
{
context.Products.Add(product);
}
else
{
context.Entry(product).State = System.Data.EntityState.Modified;
}
context.SaveChanges();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With