Just finished creating a file upload function; for images to be uploaded to a database. This is working fine.
The code below is a shortened version of the controller with just one image in it.
[HttpPost]
public ActionResult Create(CarAdvert caradvert,
HttpPostedFileBase picture1)
{
if (ModelState.IsValid)
{
if (picture1 != null)
{
string image1 = picture1.FileName;
caradvert.Image1 = image1;
var image1Path = Path.Combine(Server.MapPath("~/Content/Images"), image1);
picture1.SaveAs(image1Path);
}
db.CarAdverts.Add(caradvert);
db.SaveChanges();
return RedirectToAction("Index");
When a record is created all images upload fine; the code in the controller works, it is just when I try and edit the uploaded images the problem arises. The images will not save.
[HttpPost]
public ActionResult Edit(CarAdvert caradvert, HttpPostedFileBase picture1)
{
if (ModelState.IsValid)
{
if (picture1 != null)
{
string image1 = picture1.FileName;
caradvert.Image1 = image1;
var image1Path = Path.Combine(Server.MapPath("~/Content/Images"), image1);
picture1.SaveAs(image1Path);
}
db.Entry(caradvert).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
I think you may need to attached the "caradvert" Entity to DbContext. Try this in Edit Function.
db.CarAdverts.Attach(caradvert); // Entity is in Unchanged state
db.Entry(caradvert).State = EntityState.Modified;
db.SaveChanges();