我目前有一个编辑页面,我有一张发票。这是一张保存为二进制值的图片。
当我想编辑发票时,我希望图片保持不变,但是当我按下保存时,它会删除图像并将行更新为空。
它可能与我的编辑方法有关吗?
这是我的剃刀页面的一部分:
@{
ViewBag.Title = "Edit";
if (Model.PictureOfInvoice != null)
{
var base64 = Convert.ToBase64String(Model.PictureOfInvoice);
var imgsrc = string.Format("data:image/jpg;base64,{0}", base64);
<img src="@imgsrc" style="max-width:500px;max-height:500px" align="right" />
}
}
<h2>Details of Invoice</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Invoice</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.InvoiceId)
有没有办法不更新?
修改
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Invoice invoice = db.Invoices.Find(id);
if (invoice == null)
{
return HttpNotFound();
}
ViewBag.ChurchId = new SelectList(db.Churches, "ChurchId", "Name", invoice.ChurchId);
return View(invoice);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "InvoiceId,Company,Description,Amount,ChurchId")] Invoice invoice)
{
if (ModelState.IsValid)
{
db.Entry(invoice).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ChurchId = new SelectList(db.Churches, "ChurchId", "Name", invoice.ChurchId);
return View(invoice);
}
我的模特:
public class Invoice
{
[Key]
public int InvoiceId { get; set; }
public string Company { get; set; }
public string Description { get; set; }
public decimal Amount { get; set; }
public byte[] PictureOfInvoice { get; set; }
public string ImageFileName { get; set; }
[ForeignKey("Church")]
public int ChurchId { get; set; }
public virtual Church Church { get; set; }
public virtual Administration Admins { get; set; }
}
答案 0 :(得分:2)
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "InvoiceId,Company,Description,Amount,ChurchId")] Invoice invoice)
{
if (ModelState.IsValid)
{
Invoice oldInvoice = db.Invoices.Find(id);
oldInvoice.Amount = invoice.Amount;
// repeated for all of the properties (but not the image)
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ChurchId = new SelectList(db.Churches, "ChurchId", "Name", invoice.ChurchId);
return View(invoice);
}
关键是使用db.Invoices.Find
从数据库中获取现有项目。这样就不会丢失现有属性(如图像)。