更新产品但丢失产品 ASP.NET Core 图像

问题描述 投票:0回答:1

我从事产品的CRUD工作。我的问题是当我更新任何产品而不导入图像时,它会丢失产品的所有图像。这是我的控制器方法

Edit
Product
:

public async Task<IActionResult> Edit(int? id)
{
    if (id == null || _context.Products== null)
    {
        return NotFound();
    }

    var product = await _context.Products.FindAsync(id);

    if (product == null)
    {
        return NotFound();
    }

    return View(product);
}

// POST: Admin/Products/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit(int id, Product product)
{
    if (id != product.Id)
    {
        return NotFound();
    }
    
    string uniqueFileName1 = GetProfilePhotoFileName1(product);
    product.Image1 = uniqueFileName1;
    string uniqueFileName2 = GetProfilePhotoFileName2(product);
    product.Image2 = uniqueFileName2;
    string uniqueFileName3 = GetProfilePhotoFileName3(product);
    product.Image3 = uniqueFileName3;
    string uniqueFileName4 = GetProfilePhotoFileName4(product);
    product.Image4 = uniqueFileName4;

    _context.Update(product);
    _context.SaveChanges();

    return View(product);
}

我希望如果我更新产品但不导入任何新图像,它们将是我创建时相同的图像。但是现在当我单击编辑并保存它时,它就会丢失数据库中所有 img 的 url。

这是我的编辑观点:

edit view

有人知道这个问题以及如何解决它吗?非常感谢大家的阅读

c# asp.net-core asp.net-core-mvc
1个回答
0
投票

只需在覆盖图像的代码周围添加一个条件,检查是否设置了第一个图像。如果是这样,请执行覆盖操作。如果没有请忽略。

// POST: Admin/Products/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit(int id, Product product)
{
    if (id != product.Id)
    {
        return NotFound();
    }

    string image1 = GetProfilePhotoFileName1(product);

    if (!String.isNullOrEmpty(image1)) {
        string uniqueFileName1 = image1;
        product.Image1 = uniqueFileName1;
        string uniqueFileName2 = GetProfilePhotoFileName2(product);
        product.Image2 = uniqueFileName2;
        string uniqueFileName3 = GetProfilePhotoFileName3(product);
        product.Image3 = uniqueFileName3;
        string uniqueFileName4 = GetProfilePhotoFileName4(product);
        product.Image4 = uniqueFileName4;
    }

    _context.Update(product);
    _context.SaveChanges();

    return View(product);
}
© www.soinside.com 2019 - 2024. All rights reserved.