Implementing sorting on a table in a Blazor Server page involves a few steps. Below is a basic guide to help you achieve this. We'll cover the process for sorting a table based on a single column (asc/desc) and provide a simple, reusable approach.
Step 1: Prepare Your Data Model
First, ensure your data model is ready. For demonstration, let's use a simple Person model:
csharp
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
Step 2: Create the Table Component in Blazor
Now, create or modify your Blazor Server page to include a table. We'll add sorting functionality to the table headers.
razor
@page "/sortabletable"
<h3>Sortable Table Example</h3>
<table>
<thead>
<tr>
@* Sorting Headers *@
<th><a href="#" @onclick="(() => SortBy("Id"))">@SortIndicator("Id") Id</a></th>
<th><a href="#" @onclick="(() => SortBy("Name"))">@SortIndicator("Name") Name</a></th>
<th><a href="#" @onclick="(() => SortBy("Age"))">@SortIndicator("Age") Age</a></th>
</tr>
</thead>
<tbody>
@foreach (var person in People)
{
<tr>
<td>@person.Id</td>
<td>@person.Name</td>
<td>@person.Age</td>
</tr>
}
</tbody>
</table>
@code {
// Sample data collection
private List<Person> People = new List<Person>()
{
new Person { Id = 1, Name = "John Doe", Age = 30 },
new Person { Id = 2, Name = "Jane Doe", Age = 25 },
new Person { Id = 3, Name = "Bob Smith", Age = 40 },
};
// Current sort property and order
private string _sortBy = string.Empty;
private bool _isAscending = true;
// Handles sorting logic
private void SortBy(string propertyName)
{
// Toggle sort order if same column is clicked again
if (_sortBy == propertyName)
{
_isAscending = !_isAscending;
}
else
{
_sortBy = propertyName;
_isAscending = true; // Default to ascending for new column
}
// Use reflection to dynamically get the property info
var propertyInfo = typeof(Person).GetProperty(propertyName);
if (propertyInfo != null)
{
// Sort the list based on the specified property and order
People = _isAscending
? People.OrderBy(p => propertyInfo.GetValue(p, null)).ToList()
: People.OrderByDescending(p => propertyInfo.GetValue(p, null)).ToList();
}
// Notify Blazor to update the UI after sorting
StateHasChanged();
}
// Displays sort indicators (arrows) for the current sort column
private string SortIndicator(string propertyName)
{
if (_sortBy == propertyName)
{
return _isAscending ? " ↑" : " ↓"; // Arrows for ascending/descending
}
return string.Empty; // No indicator if not sorting by this column
}
}
Explanation:
Sorting Links in Table Headers: Each table header cell (<th>) contains a link that, when clicked, calls the SortBy method with the property name to sort by.
SortBy Method:
Toggles the sort order if the same column is clicked again.
Uses Reflection to dynamically retrieve the property info for sorting. This allows sorting by any property without hardcoded logic for each field.
Sorts the People list in ascending or descending order based on the specified property.
Calls StateHasChanged() to notify Blazor that the state has changed and the UI should be updated to reflect the sorted data.
SortIndicator Method: Displays an up arrow (↑) for ascending or a down arrow (↓) for descending sorts on the currently sorted column.
Step 3: Testing
Run your Blazor Server application.
Navigate to the /sortabletable page.
Click on the table headers to sort the data. The arrow indicators should update to reflect the sort order.
Notes:
Performance with Large Datasets: For very large datasets, consider implementing pagination to improve performance, as sorting entire large datasets can be resource-intensive. You can also use IQueryable if data comes from a database to leverage server-side sorting.
Security Consideration: When using Reflection (as in the SortBy method), ensure you validate the input (propertyName) to prevent potential security vulnerabilities, especially if the input could come from user actions in a more complex scenario. In this example, the input is hardcoded and safe, but in real-world applications:
Validate Inputs: Always validate the property names to ensure they match actual properties on the model.
Use Whitelisting: Only allow sorting on predefined, safe properties.
Avoid Exposing Sensitive Data: Ensure that sorting does not inadvertently expose sensitive data, such as internal IDs or secure information.