✅ asp.net handling image uploads.
error: NullReferenceException: Object reference not set to an instance of an object.
controller:
here is the error
here is after the error
here is the viewModel's image properties
the actual model
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"); [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"); var photoResult = await _photoService.AddPhotoAsync(_CVM.Image); var photoResult = await _photoService.AddPhotoAsync(_CVM.Image); 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");
} 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; }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; } public string? Image { get; set; }






