Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating model after HttpPost

I want to update existing Product objects in database by images, but image goes to DB successfully only when i create new objects.

I'm trying to update my object this way

[HttpPost]
public ActionResult Edit(Product product, HttpPostedFileBase image)
    {

    if (ModelState.IsValid)
        {
            if (image != null)
            {
                product.ImageMimeType = image.ContentType;
                product.ImageData = new byte[image.ContentLength];
                image.InputStream.Read(product.ImageData, 0, image.ContentLength);
            }
            if (product.ProductID != 0)
                UpdateModel<Product>(repository.Products.FirstOrDefault(p => p.ProductID == product.ProductID));
            repository.SaveProduct(product);
            TempData["message"] = string.Format("{0} has been saved", product.Name);
            return RedirectToAction("Index");
        }
        return View(product);
    }
//repository.SaveProduct()


public void SaveProduct(Product product)
        {

    if (product.ProductID == 0)
            {
                context.Products.Add(product);
            }
            context.SaveChanges();
        }

The View @ Upload new image: input type="file" name="Image" input type="submit" value="Save" @Html.ActionLink("Cancel and return to List", "Index") }

like image 638
xwrs Avatar asked May 09 '26 14:05

xwrs


1 Answers

I noticed you were read the "Pro ASP.NET MVC 3 Framework" and meet this issue same to me.

The author had a error at here, the code should be(You must reference and using the System.Data.Entity namespace at first):

    public void SaveProduct(Product product)
    {
        if (product.ProductID == 0)
        {
            context.Products.Add(product);
        }
        else
        {
            context.Entry(product).State = System.Data.EntityState.Modified;
        }

        context.SaveChanges();
    }
like image 88
Hao Hu Avatar answered May 11 '26 02:05

Hao Hu