无法更新ASP.NET Core MVC中的图像

时间:2019-11-19 08:04:41

标签: asp.net-core

我是ASP.NET Core的初学者,我正在尝试更新数据库中的图像,我对自己的代码有些疑问,图像已添加到数据库中但无法更新

AdminController

public static void main(String[] args) {
    String string1 = "Great responsibility";
    char string[] = string1.toCharArray();
    HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>();
    for (int i = 0; i < string.length; i++) {
        for (int j = i + 1; j < string.length; j++) {
            Integer value = hashMap.get(string[i]);
            if (value == null) {
                value = 1;
            }
            if (string[i] == string[j]) {
                hashMap.put(string[i], value + 1);
            } else {
                hashMap.put(string[i], value);
            }
        }
    }
    System.out.println(hashMap);
}

Edit.cshtml

public async Task<ViewResult> Edit(int productId)
        {
            return View(await _repository.Products
                .FirstOrDefaultAsync(p => p.ProductID == productId));
        }

        [HttpPost]
        public async Task<IActionResult> Edit(Product product, IFormFile image)
        {
            if (ModelState.IsValid)
            {
                if(image != null && image.Length > 0)
                {
                    var fileName = Path.GetFileName(image.FileName);
                    var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\images\\items", fileName);
                    using(var fileSteam = new FileStream(filePath, FileMode.Create))
                    {
                        await image.CopyToAsync(fileSteam);
                    }
                    product.Image = fileName;
                }
                _repository.SaveProduct(product);
                TempData["message"] = $"{product.Name} has been edit";
                return RedirectToAction("Index");
            }
            else
            {
                return View(product);
            }
        }

1 个答案:

答案 0 :(得分:0)

我发现我错了,谢谢邹兴!我更新了SaveProduct(product)

public Product SaveProduct(Product productDataUpdate)
        {
            var prod = _context.Products.Attach(productDataUpdate);
            prod.State = Microsoft.EntityFrameworkCore.EntityState.Modified;
            _context.SaveChanges();
            return productDataUpdate;
        }