[英]An unhandled exception occurred while processing the request. ASP.NET Core MVC
[英]How to solve "unhandled exception" issue while updating text field in asp.net core 5?
我已经更新了核心中的编辑功能,以根据需要更新任何字段。 有 2 个字段需要更新。 一个是文件名,另一个是图像文件。 仅更新图像文件或使用名称没有问题,但如果我只想更新名称,则会发生“未处理的异常”。
[HttpPost]
[ValidateAntiForgeryToken]
//public async Task<IActionResult> Edit([Bind("ImgID,Title,ImageFile")] IFormFile fileobj, imageModels imgModels, string fileName, int id)
public async Task<IActionResult> Edit(imageModels imgModels, int id, IFormFile ImageFile)
{
var imageModels = await _context.Images.FindAsync(id);
if (ImageFile != null)
{
var imagePath = Path.Combine(_hostEnvironment.WebRootPath, "images", imageModels.ImgName);
if (System.IO.File.Exists(imagePath))
System.IO.File.Delete(imagePath);
_context.Images.Remove(imageModels);
string wwwRootPath = _hostEnvironment.WebRootPath;
string fileName = Path.GetFileNameWithoutExtension(imgModels.ImageFile.FileName);
string extension = Path.GetExtension(imgModels.ImageFile.FileName);
imgModels.ImgName = fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension;
string path = Path.Combine(wwwRootPath + "/images/", fileName);
using (var fileStream = new FileStream(path, FileMode.Create))
{
//await imgModels.ImageFile.CopyToAsync(fileStream);
imgModels.ImageFile.CopyTo(fileStream);
}
}
_context.Update(imgModels);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
//return View(imgModels);
}
为什么要从上下文中删除imageModels
并在最后更新imageModels
。 现在,在您的上下文中,您有 2 个具有相同主键的模型,并且上下文已经在跟踪一个已被删除的模型,并将在您保存更改时从 db 中删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.