I’m re-doing an old web project with Asp.NET Core and Blazor web assembly and I’m having and issue with dynamically changing a table when the user types into the search bar. The goal is to have the table adjust it’s size and contents based on what the user has typed so far.
I’ve tried using both the onchange and oninput attributes but both result in nothing happening when I type in the search bar. I’ve also tried binding the search term to the oninput with
@bind="searchTerm" @oninput="OnSearchInput"
but I get the same result.
Here is my razor page
@page "/teams"
@inject HttpClient Http
<PageTitle>Teams</PageTitle>
<h1>Teams</h1>
<input type="text" @onchange="OnSearchInput" placeholder="Search teams..." class="searchbar" />
<p>@searchTerm</p>
@if (filteredTeams == null)
{
<p><em>Loading...</em></p>
}
else
{
<table class="table">
<thead>
<tr>
<th>Team 1</th>
<th>Team 2</th>
<th>Team 3</th>
<th>Team 4</th>
</tr>
</thead>
<tbody>
@for (int i = 0; i < filteredTeams.Count; i += 4)
{
<tr>
<td>@filteredTeams[i]</td>
<td>@(i + 1 < filteredTeams.Count ? filteredTeams[i + 1] : "")</td>
<td>@(i + 2 < filteredTeams.Count ? filteredTeams[i + 2] : "")</td>
<td>@(i + 3 < filteredTeams.Count ? filteredTeams[i + 3] : "")</td>
</tr>
}
</tbody>
</table>
}
@code {
private List<string>? teams;
private List<string>? filteredTeams;
private string searchTerm ="";
protected override async Task OnInitializedAsync()
{
teams = await Http.GetFromJsonAsync<List<string>>("team/names");
System.Diagnostics.Debug.WriteLine($"Loaded {teams?.Count} teams");
filteredTeams = teams;
}
private void OnSearchInput(ChangeEventArgs e)
{
System.Diagnostics.Debug.WriteLine("OnSearchInput triggered");
searchTerm = (string)e.Value!;
FilterTeams();
}
private void FilterTeams()
{
if (string.IsNullOrWhiteSpace(searchTerm))
{
filteredTeams = teams;
}
else
{
filteredTeams = teams?.Where(t => t.Contains(searchTerm, StringComparison.OrdinalIgnoreCase)).ToList();
}
}
}