【发布时间】:2021-06-18 22:16:10
【问题描述】:
我在 ASP.NET Core 中构建了一个 API,代码如下所示:
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");
}
}
这里我们看看它在浏览器中的样子(我猜这很好):
Blazor(服务器)代码:
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();
}
}
还有页面:
@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>
我面临空引用错误。在调试时,我看到 Applicants 为空
【问题讨论】:
-
我们无法为您调试。
-
是的,我知道,只是想如果我在这段代码中犯了某种错误,你可以告诉我
-
查看 FetchData 示例页面以及它如何使用
@if(forecasts != null) ...
标签: c# asp.net sql-server api blazor