public ActionResult Create([Bind(Include = "JeepId,JeepName,ModelYear,Package,Model,Cylendars,Doors,color")] Jeep jeep, HttpPostedFileBase upload) { if (ModelState.IsValid) { if (upload != null && upload.ContentLength > 0) { var avatar = new File { FileName = System.IO.Path.GetFileName(upload.FileName), FileType = FileType.Avatar, ContentType = upload.ContentType }; using (var reader = new System.IO.BinaryReader(upload.InputStream)) { avatar.Content = reader.ReadBytes(upload.ContentLength); } jeep.Files = new List<File> { avatar }; } db.Jeeps.Add(jeep); db.SaveChanges(); return RedirectToAction("Index"); } return View(jeep); }
public ActionResult Edit(int? id, HttpPostedFileBase upload) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } var jeepToUpdate = db.Jeeps.Include("Files").Where(j => j.JeepId == id).SingleOrDefault(); if (TryUpdateModel(jeepToUpdate, "", new string[] { "JeepId", "JeepName", "ModelYear", "Package", "Model", "Cylendars", "Doors", "color" })) { try { if (upload != null && upload.ContentLength > 0) { //Doing .ToList becasue i can not remove items from the base contatiner/collection foreach (var f in jeepToUpdate.Files.ToList()) { if (f.FileType == FileType.Avatar) { db.Files.Remove(f); } } var avatar = new File { FileName = System.IO.Path.GetFileName(upload.FileName), FileType = FileType.Avatar, ContentType = upload.ContentType }; using (var reader = new System.IO.BinaryReader(upload.InputStream)) { avatar.Content = reader.ReadBytes(upload.ContentLength); } jeepToUpdate.Files = new List<File> { avatar }; } db.Entry(jeepToUpdate).State = EntityState.Modified; db.SaveChanges(); return 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."); } } return View(jeepToUpdate); }