我有一個帶有 2 個值( PK)的模型 -
public int Id { get; set; }
public string ImageDescription { get; set; }
public byte[] Image { get; set; }
但是當用戶更新 ImageDescription 欄位時,影像會從資料庫中洗掉。我正在使用自動生成的控制器進行編輯。
public async Task<IActionResult> Edit(int id, [Bind("Id,ImageDescription")] Gallery gallery)
{
if (id != gallery.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(gallery);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!GalleryExists(gallery.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(gallery);
}
uj5u.com熱心網友回復:
您在 Bind 中沒有 Image,只有 ImageDescription,這就是您無法保存它的原因。
public async Task<IActionResult> Edit(int id, [Bind("Id,ImageDescription")] Gallery gallery)
如果您不想保存新影像并想保留以前的影像,則可以使用此代碼
var existedGallery=_context.Set<Gallery>().FirstOrDefault(i=> i.Id==gallery.Id);
if(existedGallery!=null)
{
existedGallery.ImageDescription=gallery.ImageDescription;
_context.Entry(existedGallery).Property(i => i.ImageDescription).IsModified = true;
var result = await _context.SaveChangesAsync();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/334945.html
