public async Task <IActionResult> EditAsync(int id) { this.ViewData["categories"] = _categoryRepository.Categories.Select(x => new SelectListItem { Value = x.CategoryName, Text = x.CategoryName }).ToList(); RentalAsset rentalAsset = await _rentalAssetRepository.GetItemByIdAsync(id); Category category = _categoryRepository.Categories.FirstOrDefault(p => p.CategoryId == rentalAsset.CategoryId); EditRentalAssetViewModel editRentalAssetViewModel = new EditRentalAssetViewModel { RentalAssetId = rentalAsset.RentalAssetId, Name = rentalAsset.Name, Price = rentalAsset.Price, Location = rentalAsset.Location, IsAvailable = rentalAsset.IsAvailable, Category = category.CategoryName, ExistingImagePath = rentalAsset.ImageUrl, Description = rentalAsset.Description, ExistingImages = rentalAsset.Images }; return(View(editRentalAssetViewModel)); }
public async Task <IActionResult> EditAsync(EditRentalAssetViewModel model) { if (ModelState.IsValid) { List <Image> assetImages = new List <Image>(); List <Image> deleteImages = new List <Image>(); RentalAsset rentalAsset = await _rentalAssetRepository.GetItemByIdAsync(model.RentalAssetId); Category category = _categoryRepository.Categories.FirstOrDefault(p => p.CategoryName == model.Category); rentalAsset.Name = model.Name; rentalAsset.Price = model.Price; rentalAsset.Location = model.Location; rentalAsset.CategoryId = category.CategoryId; rentalAsset.IsAvailable = model.IsAvailable; rentalAsset.DateModified = DateTime.Today; rentalAsset.Description = model.Description; if (model.Images != null) { if (model.Images.Count > 1) { if (model.ExistingImagePath != null) { string filePath = Path.Combine(_webHostEnvironment.WebRootPath + model.ExistingImagePath); System.IO.File.Delete(filePath); } foreach (var item in rentalAsset.Images) { deleteImages.Add(item); string filePath = Path.Combine(_webHostEnvironment.WebRootPath + item.ImageUrl); System.IO.File.Delete(filePath); } for (int i = 0; i < model.Images.Count; i++) { if (i == 0) { rentalAsset.ImageUrl = ProcessUploadedImage(model.Images[i]); continue; } string photoPath = ProcessUploadedImage(model.Images[i]); Image image = new Image { ImageName = model.Images[i].FileName, ImageUrl = photoPath }; assetImages.Add(image); } } rentalAsset.Images = assetImages; } await _rentalAssetRepository.EditItemAsync(rentalAsset); foreach (var item in deleteImages) { _imageRepository.DeleteImage(item); } return(RedirectToAction("List")); } return(View()); }