MVC - Don't save null image data if image was not re-uploaded in HTTP post (from SportsStore example)

可紊 提交于 2019-12-06 12:34:29

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")
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!