簡體   English   中英

更新asp.net core 5中的文本字段時如何解決“未處理的異常”問題?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM