Home > OS >  Data being lost when updating database in ASP.NET MVC
Data being lost when updating database in ASP.NET MVC

Time:10-25

I have a model with 2 values ( PK) -

public int Id { get; set; }
public string ImageDescription { get; set; }
public byte[] Image { get; set; }

But when the user updates the ImageDescription field the image gets deleted from the database. I'm using the automatically generated controller for editing.

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);
        }

CodePudding user response:

you don't have Image in Bind, only ImageDescription, this is why you can't save it.

public async Task<IActionResult> Edit(int id, [Bind("Id,ImageDescription")] Gallery gallery)

if you don't want to save the new image and want to leave the previous one, you have use this code

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();
 }
  • Related