I built an API in ASP.NET Core and the code looks like this:
public async Task<IEnumerable<Applicant>> GetApplicants()
{
return await appDbContext.Applicants.ToListAsync();
}
[HttpGet]
public async Task<ActionResult> GetApplicants()
{
try
{
return Ok(await applicantRepository.GetApplicants());
}
catch (Exception)
{
return StatusCode(StatusCodes.Status500InternalServerError, "Error retreiving data from the database");
}
}
Here we have how it looks in browser(guess that is fine):
Blazor (server) code:
public interface IApplicantService
{
Task<IEnumerable<Applicant>> GetApplicants();
}
public class ApplicantService : IApplicantService
{
private readonly HttpClient httpClient;
public ApplicantService(HttpClient httpClient)
{
this.httpClient = httpClient;
}
public async Task<IEnumerable<Applicant>> GetApplicants()
{
return await httpClient.GetJsonAsync<Applicant[]>("api/applicants");
}
}
public class ApplicantList : ComponentBase
{
[Inject]
public IApplicantService ApplicantService { get; set; }
public IEnumerable<Applicant> Applicants { get; set; }
protected override async Task OnInitializedAsync()
{
Applicants = (await ApplicantService.GetApplicants()).ToList();
}
}
And the page:
@page "/"
@inherits ApplicantList
<h1>Applicants</h1>
<div class="card-deck">
@foreach (var applicant in Applicants)
{
<div class="card m-3" style="min-width: 18rem; max-width:30.5%;">
<div class="card-header">
<h3>@applicant.Name</h3>
</div>
<div class="card-footer text-center">
<a href="#" class="btn btn-primary m-1">View</a>
<a href="#" class="btn btn-primary m-1">Edit</a>
<a href="#" class="btn btn-danger m-1">Delete</a>
</div>
</div>
}
</div>
I am facing null reference error. While debugging I see that Applicants is null