I am reading Pro ASP.NET MVC 3 Framework from Apress. I follow the example of loading and displaying images. The problem is that it works great when uploading images to products, but if I later want to edit the description, for example, and then save the product, the image will disappear. I understand that the problem is that when I save the product, I do not transfer image data, because the image loading is empty, and context.SaveChanges () saves every data field, including data fields with empty images.
I am stuck and I would really appreciate it if anyone could help me!
This is part of the edit page:
<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" />
When updating:
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); } }
Product Saving:
public void SaveProduct(Product product) { if (product.ProductID == 0) { context.Products.Add(product); } else { context.Entry(product).State = EntityState.Modified; } int result = context.SaveChanges(); }
source share