I'm on a little project to learn ASP.NET Core with Razor Pages. Here is a part of my page model with its properties
public List<Models.Student> allStudents { get; set; }
public Models.Student studentFocused { get; set; }
public async Task<IActionResult> OnGetAsync()
{
using (var _httpClient = new HttpClient())
{
using (var response = await _httpClient.GetAsync(this.uri))
{
var fetchedResponse = await response.Content.ReadAsStringAsync();
this.allStudents = JsonConvert.DeserializeObject<List<Models.Student>>(fetchedResponse);
}
}
return Page();
}
public void OnGetDetails(int id)
{
this.studentFocused = this.allStudents.Where(s => s.StudentId == id).SingleOrDefault();
}
I got OnGetAsync() which calls an API route to retrieve all students datas on a list, which is working, I can display the data in my page file like that:
<div class="row">
<div class="col-6">
<ul id="list-students">
@foreach (var student in Model.allStudents)
{
<li><span class="list-students-element">@student.FirstName @student.LastName</span><a asp-page-handler="details" asp-route-id="@student.StudentId">Détails</a></li>
}
</ul>
<div><a asp-page="/Student/Create">Créer nouvel étudiant</a></div>
</div>
<div class="col-6">
<div id="details">
@if (Model.studentFocused != null)
{
<h3>Détails</h3>
<p>Prénom: @Model.studentFocused.FirstName</p>
<p>Nom: @Model.studentFocused.LastName</p>
<p>Age: @Model.studentFocused.Age ans</p>
<p>Classe: @Model.studentFocused.SchoolClass.Name</p>
<p><strong>Options</strong></p>
<a asp-page="/Student/Update" asp-route-id="@Model.studentFocused.StudentId">Modifier</a>
<a asp-page="/Student/Delete" asp-route-id="@Model.studentFocused.StudentId">Supprimer</a>
}
</div>
</div>
</div>
But now on my <div id="details">
I want to display the details from one student when clicking on "Détails" button using the OnGetDetails() method. For that i'm searching in my allStudents property which is a list, with the ID from the wanted student. I guess the method is not complete, but just with that I got my problem:
public void OnGetDetails(int id)
{
this.studentFocused = this.allStudents.Where(s => s.StudentId == id).SingleOrDefault();
}
Got an error because this.allStudents is null here, although is initialized just before in my OnGet() so I don't understand.