✅ 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");
[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);
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");
}
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; }
28 Replies
Candyroll93
Candyroll93OP2y ago
here is the function being called
public async Task<ImageUploadResult> AddPhotoAsync(IFormFile uploadedFile)
{
var uploadResult = new ImageUploadResult();

if (uploadedFile.Length > 0)
{
using var fileStream = uploadedFile.OpenReadStream();

var uploadParams = new ImageUploadParams
{
File = new FileDescription(uploadedFile.FileName, fileStream),
Transformation = new Transformation().Height(500).Width(500).Crop("fill").Gravity("face")
};

uploadResult = await _cloudinary.UploadAsync(uploadParams);
}

return uploadResult;
}
public async Task<ImageUploadResult> AddPhotoAsync(IFormFile uploadedFile)
{
var uploadResult = new ImageUploadResult();

if (uploadedFile.Length > 0)
{
using var fileStream = uploadedFile.OpenReadStream();

var uploadParams = new ImageUploadParams
{
File = new FileDescription(uploadedFile.FileName, fileStream),
Transformation = new Transformation().Height(500).Width(500).Crop("fill").Gravity("face")
};

uploadResult = await _cloudinary.UploadAsync(uploadParams);
}

return uploadResult;
}
System.NullReferenceException: 'Object reference not set to an instance of an object.'
Candyroll93
Candyroll93OP2y ago
Candyroll93
Candyroll93OP2y ago
it looks like _photoService is null
cap5lut
cap5lut2y ago
yeah it can only be the _photoService being null, do u register the service correctly?
Candyroll93
Candyroll93OP2y ago
Candyroll93
Candyroll93OP2y ago
this is something im new to.
cap5lut
cap5lut2y ago
u also need to register the service:
using DependencyInjectionSample.Interfaces;
using DependencyInjectionSample.Services;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();

builder.Services.AddScoped<IMyDependency, MyDependency>(); // like this

var app = builder.Build();
using DependencyInjectionSample.Interfaces;
using DependencyInjectionSample.Services;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();

builder.Services.AddScoped<IMyDependency, MyDependency>(); // like this

var app = builder.Build();
(https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-7.0) also u can use $code to provide code itself
Dependency injection in ASP.NET Core
Learn how ASP.NET Core implements dependency injection and how to use it.
MODiX
MODiX2y ago
To post C# code type the following: ```cs // code here ``` Get an example by typing $codegif in chat If your code is too long, post it to: https://paste.mod.gg/
Candyroll93
Candyroll93OP2y ago
aha! tyvm let me add that in.
cap5lut
cap5lut2y ago
also, has the controller an appropriate constructor for the services?
Candyroll93
Candyroll93OP2y ago
i only have this. should i add it inside the controller constructor?
cap5lut
cap5lut2y ago
that would only inject the IClubRepository dependency, u also need to add the photo service as parameter and assign it
Candyroll93
Candyroll93OP2y ago
is this new to .7? i wonder why the tut that I'm watching didn't do this tyvm
cap5lut
cap5lut2y ago
that missing parameter is also the reason why it didnt complain at instantiation of the controller that its missing a required dependency
Candyroll93
Candyroll93OP2y ago
i may have missed it by mistake. ive been learning for three years now and switched to asp.net. i wish i started here first
cap5lut
cap5lut2y ago
there are two ways for dependency injection, via constructor or via properties. tho i only have experience with the constructor variant. (feels also cleaner to me than the properties variant)
Candyroll93
Candyroll93OP2y ago
properties as in this?
private readonly IClubRepository _clubRepository;
private readonly IPhotoService _photoService;
private readonly IClubRepository _clubRepository;
private readonly IPhotoService _photoService;
cap5lut
cap5lut2y ago
these are fields not properties. but that + the shown constructor should work, if u have registered the service as mentioned earlier
Candyroll93
Candyroll93OP2y ago
oooohhhhh i got a different error! we're in business. thats a topic i've yet to discover
cap5lut
cap5lut2y ago
note that there are 3 different methods on how u can register a service AddSingleton<TInterface, TImplementation>() -> one instance for all which require the TInterface AddTransient<TInterface, TImplementation>() -> everthing gets its own instance AddScoped<TInterface, TImplementation>() -> one instance per scope (asp creates a scope for each incoming request) with properties u can add functionality to accessing the data:
private int _someEvenValue = 0;
public int SomeEvenValue
{
get
{
Console.WriteLine("Reading SomeValue");
return _someValue;
}
set
{
if (value % 2 != 0) throw new ArgumentException("Value must be even!");
_someValue = value;
}
}
private int _someEvenValue = 0;
public int SomeEvenValue
{
get
{
Console.WriteLine("Reading SomeValue");
return _someValue;
}
set
{
if (value % 2 != 0) throw new ArgumentException("Value must be even!");
_someValue = value;
}
}
of course there is a lot more to properties, but explaining that all here would take too long ;p cant help ya if u dont give information about it, but ofc its better to try to fix it urself ;p
Candyroll93
Candyroll93OP2y ago
okay thank you very much. i greatly appreciate this. yes once i got a different error, i waws successful in fixing it.
Candyroll93
Candyroll93OP2y ago
it works now
Candyroll93
Candyroll93OP2y ago
you're the best! ❤️
cap5lut
cap5lut2y ago
glad i could help o7 also its worth reading the whole article, its a great resource on how DI works
Candyroll93
Candyroll93OP2y ago
i will read it.
cap5lut
cap5lut2y ago
if ur questions are answered please use /close to mark the thread as answered
MODiX
MODiX2y ago
Use the /close command to mark a forum thread as answered
Candyroll93
Candyroll93OP2y ago
ty again
Want results from more Discord servers?
Add your server