public ActionResult Add(ItemFormModel model) { if (ModelState.IsValid) { model.Item.UserId = WebSecurity.CurrentUserId; db.Items.Add(model.Item); db.SaveChanges(); // Save the file as {ItemId}.{extension of the file uploaded} if (model.Image != null) { // Delete old images string[] oldImages = System.IO.Directory.GetFiles(Server.MapPath("/Images/"), model.Item.ItemId + ".*"); foreach (var oldimage in oldImages) { System.IO.File.Delete(oldimage); } string extension = System.IO.Path.GetExtension(model.Image.FileName); model.Image.SaveAs(Server.MapPath("/Images/") + model.Item.ItemId.ToString() + extension); } ViewBag.Message = "Your item has successfully been added"; ViewBag.ReturnUrl = Url.Action("Index"); return View("Success"); } model.TypeList = new SelectList(db.Types, "TypeId", "Name"); return View(model); }
public ActionResult Edit(ItemFormModel model) { //Cannot edit other user's items var isValid = (from c in db.Items where c.UserId == WebSecurity.CurrentUserId select c).Any(c => c.ItemId == model.Item.ItemId); if (model.Item.UserId != WebSecurity.CurrentUserId || !isValid) { return RedirectToAction("Index", "Home"); } if (ModelState.IsValid) { db.Items.Attach(model.Item); var entry = db.Entry(model.Item); entry.State = EntityState.Modified; db.SaveChanges(); // Save the file as {ItemId}.{extension of the file uploaded} if (model.Image != null) { // Delete old images string[] oldImages = System.IO.Directory.GetFiles(Server.MapPath("/Images/"), model.Item.ItemId + ".*"); foreach (var oldimage in oldImages) { System.IO.File.Delete(oldimage); } string extension = System.IO.Path.GetExtension(model.Image.FileName); model.Image.SaveAs(Server.MapPath("/Images/") + model.Item.ItemId.ToString() + extension); } ViewBag.Message = "Your item has been edited successfully"; ViewBag.ReturnUrl = Url.Action("Index"); return View("Success"); } model.TypeList = new SelectList(db.Types, "TypeId", "Name"); return View(model); }
public ActionResult Add() { var vm = new ItemFormModel { TypeList = new SelectList(db.Types, "TypeId", "Name"), Item = new Item() }; return View(vm); }