// GET: MenuItemController/Edit/5 public async Task <IActionResult> Edit(int id) { var obj = await _repo.FindById(id); if (obj == null) { return(NotFound()); } var categories = await _catRepo.FindAll(); var categoryItems = categories.Select(q => new SelectListItem { Text = q.Name, Value = q.Id.ToString() }); var model = new EditMenuItemVM { Name = obj.Name, Description = obj.Description, Spicyness = obj.Spicyness, Category = categoryItems, CategoryId = obj.CategoryId, Price = obj.Price, CurrentPicture = obj.Image }; return(View(model)); }
public async Task <ActionResult> Edit(int id, EditMenuItemVM model) { try { var categories = await _catRepo.FindAll(); var categoryItems = categories.Select(q => new SelectListItem { Text = q.Name, Value = q.Id.ToString() }); model.Category = categoryItems; if (!ModelState.IsValid) { return(View(model)); } string uniqueFileName = model.CurrentPicture; if (model.Image != null) { string uploadsFolder = Path.Combine(_webHostEnvironment.WebRootPath, "images"); uniqueFileName = Guid.NewGuid().ToString() + "_" + model.Image.FileName; string filepath = Path.Combine(uploadsFolder, uniqueFileName); //Delete old Image var imagePath = Path.Combine(uploadsFolder, model.CurrentPicture); if (System.IO.File.Exists(imagePath)) { System.IO.File.Delete(imagePath); } using (var fileStream = new FileStream(filepath, FileMode.Create)) { model.Image.CopyTo(fileStream); } } var updateMenuItem = new MenuItemVM { Id = model.Id, Name = model.Name, Description = model.Description, Spicyness = model.Spicyness, Image = uniqueFileName, CategoryId = model.CategoryId, Price = model.Price }; var obj = _mapper.Map <MenuItem>(updateMenuItem); var success = await _repo.Update(obj); if (!success) { ModelState.AddModelError("", "Something went wrong when updating"); return(View(model)); } return(RedirectToAction(nameof(Index))); } catch { ModelState.AddModelError("", "Something went wrong with request"); return(View(model)); } }