Sorting Table In Blazor

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.

Are you looking forward to having a variety of applications built? Your best bet is to use .NET . Hire .NET developers in India to create unique online, mobile, and desktop applications. You may also use their experience in IoT, Microservices, and Machine Learning to outperform your competitors. You can handpick specialists who are knowledgeable in C#, F#, and Visual Basic at Virtual Employee. In reality, we have some of the Dedicated ASP.NET Developers & Programmers available for hire, so you can get the most out of .NET Core, .NET Framework, and Xamarin/Mono.

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.

14 Comments

  1. Gustavo Irentti

    Here from Brasil! Great article, thanks for share this!
    Work fine, lets code with Blazor!!

    0
    0
    Reply
  2. Tarik

    Excellent article and clear
    Thank you very much.

    0
    0
    Reply
    1. Thanks for feedback

      0
      0
      Reply
  3. Hairstyles

    Hi, i think that i noticed you visited my weblog thus i got here to 搟go back the desire?I’m trying to in finding things to improve my website!I guess its adequate to use a few of your ideas!!

    0
    0
    Reply
  4. Hairstyles

    Well I truly enjoyed studying it. This post provided by you is very useful for good planning.

    0
    0
    Reply
    1. It’s my pleasure. Thanks for the feedback,

      0
      0
      Reply
  5. Ray Calin

    Excellent article!

    0
    0
    Reply
    1. Thanks for the feedback!

      0
      0
      Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories