I have the following model in my Asp.Net Mvc project. When a new object is created, a new list of both Options and Foto's is also created so that you can simply add new Options and Pictures to the object.
public class VehicleModels
{
[Key]
public virtual int Id { get; set; }
public virtual string Naam { get; set; }
public virtual string Merk { get; set; }
public virtual string Brandstof { get; set; }
public virtual string Kleur { get; set; }
public virtual string TypeVanMerk { get; set; }
public virtual string TypeVanTransmissie { get; set; }
public virtual int Kilometerstand { get; set; }
public virtual int Bouwjaar { get; set; }
public virtual int AantalDeuren { get; set; }
public List<Optie> Options { get; set; }
public List<Foto> Fotos { get; set; }
public VehicleModels()
{
Options = new List<Optie>();
Fotos = new List<Foto>();
}
}
I have this Edit in my Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int? id, HttpPostedFileBase upload)
{
if (id == null)
{
retu new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var VehicleToUpdate = db.VehicleModels.Find(id);
if (TryUpdateModel(VehicleToUpdate))
{
try
{
if (upload != null && upload.ContentLength > 0)
{
if (VehicleToUpdate.Fotos.Any(f => f.VehicleModelsID == VehicleToUpdate.Id))
{
db.Fotos.Remove(VehicleToUpdate.Fotos.First(f => f.VehicleModelsID == VehicleToUpdate.Id));
}
var picture = new Foto
{
FotoNaam = System.IO.Path.GetFileName(upload.FileName),
ContentType = upload.ContentType
};
using (var reader = new System.IO.BinaryReader(upload.InputStream))
{
picture.Content = reader.ReadBytes(upload.ContentLength);
}
VehicleToUpdate.Fotos.Add(picture);
}
db.Entry(VehicleToUpdate).State = EntityState.Modified;
db.SaveChanges();
retu RedirectToAction("Index");
}
catch (RetryLimitExceededException /* dex */)
{
//Log the error (uncomment dex variable name and add a line here to write a log.
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
}
}
retu View(VehicleToUpdate);
}
My Problem:
While debugging i found that this line of code (var VehicleToUpdate = db.VehicleModels.Find(id);) inside my Edit method creates a new object of the model and seems to bind the properties to that new object. But because it passes the constructor, both lists are wiped clean.
The problem shows itself when i try to change the picture of the object, because the list is empty, it does not delete any and it also does not add the new image, instead it just adds the old image again, leaving me with 2x the same image.
Should i instantiate my Lists somewhere else? If so, where would be the appropriate place?
Side note: I followed this tutorial to add images to my project.
