In this article, we are going to sorting on the table. In my previous article, I walked through CRUD Using Blazor, Entity Framework Core And Dapper. If you haven’t read yet please read that article first in order to understand this article. You can download the CRUD Blazor code from here. If you are new to Blazor, I recommend to read Getting Started With Blazor.

So, in this article we will implement the following things:

  • Sort “ID” and “Title” columns in ascending and descending order.
  • DIsplay sorting icon based on sort column and direction.

Let’s start!

First, add a font-awesome CDN link in our “FetchArticle.razor” page.

<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

Now, display header sortable with pointer cursor and make a sort icon to the right of the cell, with the help of following CSS.

<style>
    .sort-th {
        cursor: pointer;
    }

    .fa {
        float: right;
    }
</style>

Your “FetchArticle.razor” page will look like this.

When a user clicks on a column, we need to sort that column and display a correct sorting icon, to do this we will create the following functions inside @code { } block.

First, declare two wearables to get sort column and know sorting direction.

private bool isSortedAscending;
private string activeSortColumn;

Create a Sorting method to sort data on the user’s selected column.

private void SortTable(string columnName)
    {
        if (columnName != activeSortColumn)
        {
            articleModel = articleModel.OrderBy(x => x.GetType().GetProperty(columnName).GetValue(x, null)).ToList();
            isSortedAscending = true;
            activeSortColumn = columnName;

        }
        else
        {
            if (isSortedAscending)
            {
                articleModel = articleModel.OrderByDescending(x => x.GetType().GetProperty(columnName).GetValue(x, null)).ToList();
            }
            else
            {
                articleModel = articleModel.OrderBy(x => x.GetType().GetProperty(columnName).GetValue(x, null)).ToList();
            }

            isSortedAscending = !isSortedAscending;
        }
    }

Set a proper icon on the sorted column. To do this let’s create following method.

private string SetSortIcon(string columnName)
    {
        if (activeSortColumn != columnName)
        {
            return string.Empty;
        }
        if (isSortedAscending)
        {
            return "fa-sort-up";
        }
        else
        {
            return "fa-sort-down";
        }
    }

Let’s modified Html content.

In the Table, tag add “class=”table table-bordered table-hover” property.

<table class="table table-bordered table-hover">

for headers(<thead>) add “class=”sort-th” property, add method @onclick=”@(() => SortTable(“Your Column Name”))” and for icon add <span class=”fa @(SetSortIcon(“Your Column Name”))”></span>

For this example, our table will looks like this,

<table class="table table-bordered table-hover">
        <thead>
            <tr>
                <th class="sort-th" @onclick="@(() => SortTable("ID"))">
                    ID
                    <span class="fa @(SetSortIcon("ID"))"></span>
                </th>
                <th class="sort-th" @onclick="@(() => SortTable("Title"))">
                    Title
                    <span class="fa @(SetSortIcon("Title"))"></span>
                </th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var article in articleModel)
            {
                <tr>
                    <td>@article.ID</td>
                    <td>@article.Title</td>
                    <td>
                        <a class="btn btn-primary" href='/editArticle/@article.ID'>Edit</a>  |
                        <a class="btn btn-danger" @onclick="() => DeleteArticle(article.ID)">Delete</a>
                    </td>
                </tr>
            }
        </tbody>
    </table>

Full code of “FetchArticle.razor” page.

@page "/articlelist"

@using BlazorCRUD.Entities
@using BlazorCRUD.Contracts
@inject IArticleManager articleManager

<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

<style>
    .sort-th {
        cursor: pointer;
    }

    .fa {
        float: right;
    }
</style>

<div>
    <a class="btn btn-primary" href='/addArticle'>Add</a>
</div>
<br />

@if (articleModel == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table table-bordered table-hover">
        <thead>
            <tr>
                <th class="sort-th" @onclick="@(() => SortTable("ID"))">
                    ID
                    <span class="fa @(SetSortIcon("ID"))"></span>
                </th>
                <th class="sort-th" @onclick="@(() => SortTable("Title"))">
                    Title
                    <span class="fa @(SetSortIcon("Title"))"></span>
                </th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var article in articleModel)
            {
                <tr>
                    <td>@article.ID</td>
                    <td>@article.Title</td>
                    <td>
                        <a class="btn btn-primary" href='/editArticle/@article.ID'>Edit</a>  |
                        <a class="btn btn-danger" @onclick="() => DeleteArticle(article.ID)">Delete</a>
                    </td>
                </tr>
            }
        </tbody>
    </table>
}


@code {
    List<Article> articleModel;
    Article articleEntity = new Article();

    protected override async Task OnInitializedAsync()
    {
        articleModel = await articleManager.ListAll();
    }


    protected async Task DeleteArticle(int id)
    {
        await articleManager.Delete(id);
        articleModel = await articleManager.ListAll();
    }

    private bool isSortedAscending;
    private string activeSortColumn;

    private void SortTable(string columnName)
    {
        if (columnName != activeSortColumn)
        {
            articleModel = articleModel.OrderBy(x => x.GetType().GetProperty(columnName).GetValue(x, null)).ToList();
            isSortedAscending = true;
            activeSortColumn = columnName;

        }
        else
        {
            if (isSortedAscending)
            {
                articleModel = articleModel.OrderByDescending(x => x.GetType().GetProperty(columnName).GetValue(x, null)).ToList();
            }
            else
            {
                articleModel = articleModel.OrderBy(x => x.GetType().GetProperty(columnName).GetValue(x, null)).ToList();
            }

            isSortedAscending = !isSortedAscending;
        }
    }

    private string SetSortIcon(string columnName)
    {
        if (activeSortColumn != columnName)
        {
            return string.Empty;
        }
        if (isSortedAscending)
        {
            return "fa-sort-up";
        }
        else
        {
            return "fa-sort-down";
        }
    }

}

Tada! We completed sorting on the table, when you run the app, you will see below output in the browser.

sorting-table-in-blazor-output.gif

You can download source code from here.

If you want to learn File Upload in Blazor please visit here. and want to apply for pagination on table visit here.

I hope you guys found something useful. Please give your valuable feedback/comments/questions about this article. Please let me know how you like and understand this article and how I could improve it.