✅ asp.net handling image uploads.

error: NullReferenceException: Object reference not set to an instance of an object.
controller:
 [HttpPost]
        public async Task<IActionResult> Edit(int Id, ClubViewModel _CVM)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("", "Failed to edit this club");

                return View("Edit", _CVM);
            }

            var clubUploadingImage = await _clubRepository.GetByIdAsync(Id);

            if (clubUploadingImage == null) return View("Error");
here is the error
            var photoResult = await _photoService.AddPhotoAsync(_CVM.Image);
here is after the error
            if (photoResult.Error != null)
            {
                ModelState.AddModelError("Image", "Unable to upload photo");
                return View(_CVM);
            }

            if (clubUploadingImage.Image == null)
            {
                _ = await _photoService.DeletePhotoAsync(clubUploadingImage.Image);
            }

            var updateClubImage = new Club()
            {
                Id = _CVM.Id,
                Title = _CVM.Title,
                Description = _CVM.Description,
                Image = photoResult.Url.ToString(),
                AddressId = _CVM.AddressId,
                Address = _CVM.Address,
                ClubCategory = _CVM.ClubCategory,
            };

            _clubRepository.Update(updateClubImage);

            return RedirectToAction("Index");
        }

here is the viewModel's image properties
public class ClubViewModel
    {
        public int Id { get; set; } // [Key] not required if the id is declared like this
        public string? Title { get; set; }
        public string? Description { get; set; }
        public IFormFile Image { get; set; }
 public string? ImageURL { get; set; }

the actual model
        public string? Image { get; set; }
Was this page helpful?