public ActionResult Create([Bind(Include = "CarTypeId,CarCode,DailyPrice,DailyLatePrice")] CarType carType, HttpPostedFileBase upload) { if (ModelState.IsValid) { if (upload != null && upload.ContentLength > 0) { var carImage = new File { FileName = System.IO.Path.GetFileName(upload.FileName), FileType = FileType.CarImage, ContentType = upload.ContentType }; using (var reader = new System.IO.BinaryReader(upload.InputStream)) { carImage.Content = reader.ReadBytes(upload.ContentLength); } carType.Files = new List<File> { carImage }; } db.CarTypes.Add(carType); db.SaveChanges(); TempData["Added"] = carType.CarCode + " Added"; return RedirectToAction("Index"); } return View(carType); }
//public ActionResult Edit(CarType carType, HttpPostedFileBase upload) public ActionResult Edit(int? id, HttpPostedFileBase upload) { //if (ModelState.IsValid) //{ if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } var carType = db.CarTypes.Find(id); if (TryUpdateModel(carType, "", new string[] { "CarCode", "DailyPrice", "DailyLatePrice", "Comments" })) { if (upload != null && upload.ContentLength > 0) { if (carType.Files.Any(f => f.FileType == FileType.CarImage)) { db.Files.Remove(carType.Files.First(f => f.FileType == FileType.CarImage)); } var carImage = new File { FileName = System.IO.Path.GetFileName(upload.FileName), FileType = FileType.CarImage, ContentType = upload.ContentType }; using (var reader = new System.IO.BinaryReader(upload.InputStream)) { carImage.Content = reader.ReadBytes(upload.ContentLength); } carType.Files = new List<File> { carImage }; db.Entry(carType).State = EntityState.Modified; } db.Entry(carType).State = EntityState.Modified; db.SaveChanges(); TempData["Added"] = carType.CarCode + " Edited"; return RedirectToAction("Index"); } return View(carType); }