I have been following the SportsStore example project in Apress Pro ASP.NET MVC 3 Framework book and trying to apply the concepts to my application. One area that is bugging me is that in the sample, I can add an image to a product and it gets saved to the database, but if I edit any given product, without uploading a new image for it, the image data is cleared out. I want to be able to edit a product, but if the image data returned from the HTTP post is null, that I want Entity Framework to keep the exisiting image data (and content type). How can I command EF to not update this image field with null if a new image isn't uploaded?
Here is the Edit code from the SportsStore sample:
[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);
}
_repository.SaveProduct(product);
TempData["message"] = string.Format("{0} has been saved", product.Name);
return RedirectToAction("Index");
}
else
{
return View(product);
}
}
EDIT: For Rondel - Here is the definition of the Product class
namespace SportsStore.Domain.Entities
{
public class Product
{
[HiddenInput(DisplayValue=false)]
public int ProductId { get; set; }
[Required(ErrorMessage = "Please enter a product name")]
public string Name { get; set; }
[Required(ErrorMessage = "Please enter a description")]
[DataType(DataType.MultilineText)]
public string Description { get; set; }
[Required]
[Range(0.01, double.MaxValue, ErrorMessage = "Please enter a positive price")]
public decimal Price { get; set; }
[Required(ErrorMessage = "Please specify a category")]
public string Category { get; set; }
public byte[] ImageData { get; set; }
[HiddenInput(DisplayValue = false)]
public string ImageMimeType { get; set; }
}
}
EDIT How can I make EF save only certain fields and leave others untouched in the database?
The basic problem here is that when you save the Product
back to the database, you are overwriting the ImageMimeType
and ImageData
fields with whatever values MVC3 populates that Product
with from the FormCollection
. Right now you have a check to see if the image==null
but you did not implement the logic to reuse the old Product
image information. Here is what you want to do:
if (ModelState.IsValid)
{
if(image != null)
{
product.ImageMimeType = image.ContentType;
product.ImageData = new byte[image.ContentLength];
image.InputStream.Read(product.ImageData, 0, image.ContentLength);
}
else
{
//set this Product image details from the existing product in the db
product.ImageMimeType= getImageMimeTypeForProduct(product.ProductId );
product.ImageData = getImageDataForProduct(product.ProductId );
}
_repository.SaveProduct(product);
TempData["message"] = string.Format("{0} has been saved", product.Name);
return RedirectToAction("Index");
}
else
{
return View(product);
}
Obviously those two methods don't really exist but the idea is the same. You want to get the existing values from the db for that Product and ensure that those are reflected in the local version of the Product
before you save it and overwrite the values.
I know its a bit late in replying but I'm just working through this chapter now and had the same issue.
I fixed it by adding a hidden field to the edit view to hold the ImageData data. As the view uses @Html.EditorForModel this does not render any editor for a byte data type, therefore the view has no visibility of this data.
@model SportsStore.Domain.Entities.Product
@{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_AdminLayout.cshtml";
}
<h1>Edit @Model.Name</h1>
@using (Html.BeginForm("Edit", "Admin", FormMethod.Post, new { enctype = "multipart/form-data"}))
{
@Html.EditorForModel()
// New hidden field here
@Html.Hidden("ImageData", Model.ImageData)
<div class="editor-label">Image</div>
<div class="editor-field">
@if (Model.ImageData == null)
{
@:None
}
else
{
<img width="150" height="150" src="@Url.Action("GetImage", "Product", new { Model.ProductID})" />
}
<div>Upload new image: <input type="file" name="Image" /></div>
</div>
<input type="submit" value="Save" />
@Html.ActionLink("Cancel and return to List", "Index")
}
来源:https://stackoverflow.com/questions/8649287/mvc-dont-save-null-image-data-if-image-was-not-re-uploaded-in-http-post-from