public ActionResult Create(Students model, HttpPostedFileBase StudentPhoto) { try { if (ModelState.IsValid) { string tryCatchFileName = string.Empty; try { using (ImageUploader imageUploader = new ImageUploader()) { //string fileName = StudentPhoto.FileName.Replace(' ', '-') + "-" + DateTime.Now.Ticks; string fileName = Guid.NewGuid().ToString("N") + '-' + StudentPhoto.FileName; string location = Server.MapPath("~/Content/StudentPhotos"); model.StudentPhoto = "/Content/StudentPhotos/" + imageUploader.UploadImage(StudentPhoto, fileName.Trim(), location); tryCatchFileName = fileName; } } catch (Exception ex) { using (ImageUploader imageUploader = new ImageUploader()) { imageUploader.DeleteImage(tryCatchFileName); } AddModelErrors(ex.Message); return(View(model)); } model.Date_Of_Admission = DateTime.Now; model.Year_Of_Admission = DateTime.Now.Year.ToString(); db.Students.Add(model); db.SaveChanges(); ModelState.Clear(); return(RedirectToAction("Index")); } else { AddModelErrors(); return(View(model)); } } catch (Exception ex) { ModelState.AddModelError("", ex.Message); return(View(model)); } }
public ActionResult Edit(int?id, string ProfilePic, /*[Bind(Exclude = "Date_Of_Admission,Year_Of_Admission,Student_Status_ID")]*/ Students model, HttpPostedFileBase StudentPhoto) { try { if (id == null) { AddModelErrors(); return(View(model)); } if (ModelState.IsValid) { try { var student = db.Students.Attach(model); var studentEntry = db.Entry(model); string tryCatchFileName = string.Empty; try { //Upload StudentPhoto here. if (StudentPhoto != null) { using (ImageUploader imageUploader = new ImageUploader()) { //string fileName = StudentPhoto.FileName.Replace(' ', '-') + "-" + DateTime.Now.Ticks; ; string fileName = Guid.NewGuid().ToString("N") + '-' + StudentPhoto.FileName; string location = Server.MapPath("~/Content/StudentPhotos"); model.StudentPhoto = "/Content/StudentPhotos/" + imageUploader.UploadImage(StudentPhoto, fileName.Trim(), location); tryCatchFileName = fileName; imageUploader.DeleteImage(ProfilePic); } } else { model.StudentPhoto = ProfilePic; } } catch (Exception ex) { using (ImageUploader imageUploader = new ImageUploader()) { imageUploader.DeleteImage(tryCatchFileName); } AddModelErrors(ex.Message); return(View(model)); } studentEntry.State = EntityState.Modified; db.SaveChanges(); ModelState.Clear(); return(RedirectToAction("Index")); } catch (Exception ex) { AddModelErrors(ex.Message); return(View(model)); } } AddModelErrors(); return(View(model)); } catch (Exception ex) { AddModelErrors(ex.Message); return(View(model)); } }