CB4
CB4

Reputation: 748

MVC 5 - trying to modify the image via Edit action fail

Here is my model class

public class Data
{
    public int ID { get; set; }
    public string Name { get; set; }
    public byte[] Image { get; set; }
}

Here is my Edit HttpPost method

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ID,Name,Image")] Data data, HttpPostedFileBase image1)
{
    if(ModelState.IsValid)
    {
        if(image1 != null)
        {
            data.Image = new byte[image1.ContentLength];
            image1.InputStream.Read(data.Image, 0, image1.ContentLength);
        }
        else
        {
            data.Image = db.Data.Find(data.ID).Image;
        }

        db.Entry(data).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
   }

   return View(data);

}

My problem is that in the Edit HttpPost if I don't specify a new image file then I would get the following error when try to Save.

Error

However, if I supply a new image in the Edit page then the code works.

I'd very appreciated if you could tell me what I done wrong here.

Thank you.

Upvotes: 1

Views: 80

Answers (2)

Alexander Taran
Alexander Taran

Reputation: 6725

Seems like you have it a bit upside down. Seems like you are only updating name and image if that was supplied. And Id - you always have. Why don't you just :

if(ModelState.IsValid)
{
     var dbData = db.Data.Find(data.ID);
     dbData.Name = data.Name

     if(image1 != null)
     {
          dbData.Image = new byte[image1.ContentLength];
          image1.InputStream.Read(dbData.Image, 0, image1.ContentLength);
     }              

        db.SaveChanges();
        return RedirectToAction("Index");
}

return View(data);

and optimize later when it will be needed.

Upvotes: 2

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

You are not attaching the object with context,so what is happening is that it trying to insert a new row instead of updating, you need to do like:

db.Data.Attach(data);
db.Entry(data).State = EntityState.Modified;
db.SaveChanges();

Upvotes: 2

Related Questions