I have a Blazor component that displays data from SQL in an unordered list.
The LoadData method is called by the OnInitialized() event and populates a List<T> (in this case, a list of ProjectModels). The data volume is large, therefore I only fetch the top 100 rows from SQL (meant as a preview).
I iterate over that list with a foreach and create a <li> for each element.
This works fine.
However, the page also contains a search box. Once the user enters a search string and clicks the search button, a different method is called that gets data from SQL again, this time filtering by the user-provided search term. The filtering is done in the SQL query. The query result is again used to populate the list of ProjectModels (it overwrites the first instance of the list).
I can see the new, filtered list for a millisecond, then the initial data pops back up. I guess this is because OnInitialized is triggered again, which contains the query that populates the list with the initial data.
This is what my component looks like:
@page "/projects"
<form>
<input type="search" placeholder="enter search term..." @bind-value="searchTerm">
<button type="submit" @onclick="GetSearchResults">Search</button>
</form>
<ul>
@foreach (var project in projects)
{
<li>@project.ProjectId</li>
<li>@project.ProjectTitle</li>
}
</ul>
@code {
private string searchTerm;
private List<ProjectModel> projects = new List<ProjectModel>();
protected override void OnInitialized()
{
projects = GetProjects(); //the method that loads the inital data
}
private void GetSearchResults()
{
projects = GetProjectsBySearchTerm(searchTerm);
}
}
How can I do this correctly? i.e.
- Get the initial preview data on page load and put it in a
<ul> - replace the data in the
<ul>with the data that was queried based on the provided search term while avoiding that the initial load is triggered once the data changes.
C# and Blazor noob here, so please go easy and let me know if I need to provide more details. thanks to all of you.