ASP.NET Core Blazor Filtering And Sorting Using Entity Framework And Web API

Introduction

ASP.NET Core

This article will explain in detail how to create an ASP.NET Core Blazor Filter and Sorting for HTML Table using Entity Framework and Web API.

This article will explain.

  1. How to create an ASP.NET Core Blazor Web application.
  2. How to install the Package for using Entity Framework and creating a DBContext class.
  3. How to get a result from Web API and bind result in Blazor client Razor view
  4. Adding Sorting and Filtering features for the HTML table

Prerequisites

Make sure, you have installed all the prerequisites on your computer. If not, then download and install them all, one by one. Note that since Blazor is a new framework we must have installed a preview of Visual Studio 2017 (15.7) or above.

Step 1. Create a database and a table.

We will be using our SQL Server database for our WEB API and EF. First, we create a database named StudentsDB and a table as StudentMaster. Here is the SQL script to create a database table and sample record insert query in our table. Run the query given below in your local SQL Server to create a database and a table to be used in our project.

USE MASTER
GO

-- 1) Check for the Database Exists .If the database is exist then drop and create new DB
IF EXISTS (SELECT [name] FROM sys.databases WHERE [name] = 'StudentsDB' )
DROP DATABASE StudentsDB
GO

CREATE DATABASE StudentsDB
GO

USE StudentsDB
GO

-- 1) //////////// StudentMasters

IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = 'StudentMasters' )
DROP TABLE StudentMasters
GO

CREATE TABLE [dbo].[StudentMasters](
    [StdID] INT IDENTITY PRIMARY KEY,
    [StdName] [varchar](100) NOT NULL,
    [Email]  [varchar](100) NOT NULL,
    [Phone]  [varchar](20) NOT NULL,
    [Address]  [varchar](200) NOT NULL
)

-- insert sample data to Student Master table

INSERT INTO [StudentMasters]   ([StdName],[Email],[Phone],[Address])
    VALUES ('Shanu','[email protected]','01030550007','Madurai,India')

INSERT INTO [StudentMasters]   ([StdName],[Email],[Phone],[Address])
    VALUES ('Afraz','[email protected]','01030550006','Madurai,India')

INSERT INTO [StudentMasters]   ([StdName],[Email],[Phone],[Address])
    VALUES ('Afreen','[email protected]','01030550005','Madurai,India')


    select * from [StudentMasters]   

Step 2. Create ASP.NET Core Blazor Application

After installing all the prerequisites listed above and ASP.NET Core Blazor Language Services, click Start >> Programs >> Visual Studio 2017 >> Visual Studio 2017 on your desktop. Click New >> Project. Select Web >> ASP.NET Core Angular Web Application. Enter your project name and click OK.

 ASP.NET Core Blazor Language Services

Select Blazor (ASP.NET Core hosted) and click ok.

 ASP.NET Core hosted

After creating the ASP.NET Core Blazor Application, wait for a few seconds. You will see the below structure in Solution Explorer.

 Solution Explorer

What is new in the ASP.NET Core Blazor solution?

When we create our new ASP.NET Core Blazor application we can see there will be 3 projects which will be automatically created in the Solution Explorer.

Client Project

The first project created the Client project and it will be our Solution name. Client and here we can see our Solution name is “BlazorASPCORE”. As the project is named as a client this project will be mainly focused on all the client-side views. Here, we will be adding all our page views to be displayed on the client side in the browser.

BlazorASPCORE

We can see a few sample pages have been already added here and we can also see a shared folder like our MVC application where we will have the Shared folder and Layout page for the Master page. Here in Blazor, we have the MainLayout which will be working like the Master page and NavMenu for the left side menu displayed.

Server Project

As the name indicates, this project will be used as a Server project. This project is mainly used to create all our Controllers and WEB API Controllers to perform all business logic and perform CRUD operations using WEB-APIs. In our demo application, we will be adding a Web API in this Server project and all the WEB API in our Client application. This Server project will be working to get/set the data from the Database and from our Client project we bind or send the result to this server to perform the CRUD operation in the database.

Server Project

Shared Project

As the name indicates this project works like a shred project. This project works as a Model for our Server project and for the Client project. The Model declared in this Shared project will be used in both the Server and the Client project. We also install all the packages needed for our project here, for example, to use the Entity Framework we install all the packages in this Shared project.

Shared Project

Run to test the application

When we run the application, we can see that the left side has navigation and the right side contains the data. We can see the default sample pages and menus will be displayed on our Blazor website. We can use the page or remove it and start with our own page.

Weather forecast

Now, let’s see how to add a new page to perform the CRUD operation for maintaining student details.

Using Entity Framework

To use the Entity Framework in our Blazor application we need to install the below packages.

Install the Packages

Go to Tools and then select -> NuGet Package Manager -> Package Manager Console.

NuGet Package Manager

You can see the Console at the bottom of the VS 2017 IDE and on the right side of the combobox on the console select the Default project as your shared project "Select Shared”.

Default project

You can see the PM> and copy and paste the below line to install the Database Provider package. This package is used to set the database provider as SQL Server

Install-Package Microsoft.EntityFrameworkCore.SqlServer

Database Provider package

We can see that the package is installed in our Shared folder.

Install the Entity Framework

You can see the PM> and copy and paste the below line to install the EF package.

Install-Package Microsoft.EntityFrameworkCore.Tools

EF package

Create DB Context and set the DB Connection string

You can see the PM> and copy and paste the below line, set the Connection string, and create DB Context. This is an important part as we give our SQL Server name, Database Name SQL server UID, and SQL Server Password to connect to our database for performing the CRUD operation. We also give our SQL Table name to create the Model class in our Shared project.

Scaffold-DbContext "Server=YourSqlServerName;Database=StudentsDB;user id=YourSqlUID;password=YourSqlPassword;Trusted_Connection=True;MultipleActiveResultSets=true" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Tables StudentMasters

DB Connection string

Press enter to create a connection string, Model Class, and Database Context.

Database Context

We can see StudentMasters Model class and StudentsDBContext class has been created in our Shared project. We will be using this Model and DBContext in our Server project to create our Web API to perform the CRUD operations. 

Creating Web API to Get Student Details

To create our WEB API Controller, right-click the Controllers folder. Click Add New Controller.

New Controller

Here we will be using the Scaffold method to create our WEB API. We select API Controller with actions, using Entity Framework.

WEB API

Select our Model and DatabaseContext from the Shared project.

DatabaseContext

Select our StudentMasters Model from the Shared Project for performing the CRUD operation.

CRUD operation

Select the Data Context Class as our StudentsDBContext from the Shared project. Our Controller name will be automatically added if you need to you can change it and click  ADD.

StudentsDBContext

We will be using only the Get method from our Web API.

Get method

To test the Get Method, we can run our project and copy the GET method API path. Here, we can see our API path to get API/StudentMasters/

Run the program and paste the API path to test our output.

API path

Now, we will bind all the WEB API JSON results in our View page from our Client project

Working with Client Project

First, we need to add the new Razor view page.

Add Razor View

To add the Razor view page click the Pages folder from the Client project. Click on Add >> New Item

Add Razor View

Select Razor View >> Enter your page name, Here we have given the name Students. C Html

Select Razor View

In Razor view Page we have 3 parts of code. The first one is the Import part where we import all the references and models for use in the view, HTML design, and data binding part and finally, we have the function part to call all the web APIs to bind in our HTML pages and also to perform client-side business logic to be displayed in the View page.

Import part

First, we import all the needed support files and references into our Razor View page. Here we have first imported our Model class to be used in our view and also imported HTTPClient for calling the Web API to perform the CRUD operations.

@using BLAZORASPCORE.Shared
@using BLAZORASPCORE.Shared.Models
@page "/Students"
@using Microsoft.AspNetCore.Blazor.Browser.Interop
@inject HttpClient Http

ASP.NET Core pages

HTML design and data Binding part

Next, we design our Student details page to bind the student details from the Web API to the HTML table.

Adding Sorting features in Table Heading

In the Table heading part for each heading we add the Sorting Image. In the Sorting Image Button Click event we call the Sorting function and pass each Sorting Column name to the click event. In the Function code part, we sort the Web API and display the results in ascending and descending order by each column header.

<table style="background-color:#FFFFFF; border-style:inset; border-width:1px; border-color:#6D7B8D; padding:2px; width:100%; table-layout:fixed;" cellpadding="1" cellspacing="1">
    <tr style="background-color:#2d364d ; color:#FFFFFF ; border-style:dashed; border-width:2px; border-color:0A2464 ;">
        <td width="30" align="center"></td>
        <td width="80" align="center">
            <img src="@ImageSortname" onclick="@(async () => await StudentSorting("StdId"))" height="24" width="24"/>
            Student ID
        </td>
        <td width="240" align="center">
            <img src="@ImageSortname" onclick="@(async () => await StudentSorting("StdName"))" height="24" width="24"/>
            Student Name
        </td>
        <td width="240" align="center">
            <img src="@ImageSortname" onclick="@(async () => await StudentSorting("Email"))" height="24" width="24"/>
            Email
        </td>
        <td width="120" align="center">
            <img src="@ImageSortname" onclick="@(async () => await StudentSorting("Phone"))" height="24" width="24"/>
            Phone
        </td>
        <td width="340" align="center">
            <img src="@ImageSortname" onclick="@(async () => await StudentSorting("Address"))" height="24" width="24"/>
            Address
        </td>
    </tr>
</table>

Adding Filtering features in Table Heading

In the Table heading part we add a new row. In the table row, we add the Textbox for each column to perform the filtering for the bound result. In the Textbox onChange event we call the method to perform the Filtering operation from the code function part

<tr style="height: 30px; background-color:#336699 ; color:#FFFFFF ;">
    <td width="30" align="center"></td>
    <td width="80" align="center">Filter :</td>
    <td width="240" align="center">
        <input width="70" onchange=@OnstdNameChanged oninput="(this.dispatchEvent(new CustomEvent('change', {bubbles: true})))" />
    </td>
    <td width="240" align="center">
        <input width="70" onchange=@OnEmailChanged oninput="(this.dispatchEvent(new CustomEvent('change', {bubbles: true})))" />
    </td>
    <td width="120" align="center">
        <input width="70" onchange=@OnPhoneChanged oninput="(this.dispatchEvent(new CustomEvent('change', {bubbles: true})))" />
    </td>
    <td width="340" align="center">
        <input width="70" onchange=@OnAddressChanged oninput="(this.dispatchEvent(new CustomEvent('change', {bubbles: true})))" />
    </td>
</tr>

Bind the result

We bind the Web API result in the HTML component part.

@foreach (var StudentMasters in stdMaster)
{
    <tr style="border-style: dashed; border-width: 2px; border-color: #659EC7;">
        <td align="center" style="border: solid 1px #659EC7; padding: 5px; table-layout: fixed;">


        </td>
        <td align="center">
            <span style="color:#9F000F">
                @StudentMasters.StdId
            </span>
        </td>
        <td align="center">
            <span style="color:#9F000F">
                @StudentMasters.StdName
            </span>
        </td>
        <td align="center">
            <span style="color:#9F000F">
                @StudentMasters.Email
            </span>
        </td>
        <td align="center">
            <span style="color:#9F000F">
                @StudentMasters.Phone
            </span>
        </td>
        <td align="center">
            <span style="color:#9F000F">
                @StudentMasters.Address
            </span>
        </td>
    </tr>
}

Function Part

The function part is to call all the web APIs to bind in our HTML page and also to perform client-side business logic to be displayed on the View page.

Init Method

In the Init method, we get the result of Web API for student details and store it in the StudentMaster object and we use this object to be bound in our HTML table for each statement.

@functions {
    StudentMasters[] stdMaster;

    StudentMasters stdmst = new StudentMasters();

    int ids = 0;
    int studentIDs = 0;
    string ImageSortname = "Images/sortAsc.png";

    protected override async Task OnInitAsync()
    {
        stdMaster = await Http.GetJsonAsync<StudentMasters[]>("/api/StudentMasters/");
    }
}

Sorting Method

In the Sorting image click on each column heading; we call this method and pass the column name to this method. This method depends on the column name. We sort the Web API result and bind the result in the HTML table. We also do the reverse sorting of ascending and descending.

// Sorting
protected async Task StudentSorting(string SortColumn)
{
    stdMaster = await Http.GetJsonAsync<StudentMasters[]>("/api/StudentMasters/");

    if (ids == 0)
    {
        ImageSortname = "Images/sortDec.png";
        ids = 1;

        switch (SortColumn)
        {
            case "StdId":
                stdMaster = stdMaster.OrderBy(x => x.StdId).ToArray();
                break;
            case "StdName":
                stdMaster = stdMaster.OrderBy(x => x.StdName).ToArray();
                break;

            case "Email":
                stdMaster = stdMaster.OrderBy(x => x.Email).ToArray();
                break;
            case "Phone":
                stdMaster = stdMaster.OrderBy(x => x.Phone).ToArray();
                break;
            case "Address":
                stdMaster = stdMaster.OrderBy(x => x.Address).ToArray();
                break;

        }
    }
    else
    {
        ImageSortname = "Images/sortAsc.png";
        ids = 0;

        switch (SortColumn)
        {
            case "StdId":
                stdMaster = stdMaster.OrderByDescending(x => x.StdId).ToArray();
                break;
            case "StdName":
                stdMaster = stdMaster.OrderByDescending(x => x.StdName).ToArray();
                break;

            case "Email":
                stdMaster = stdMaster.OrderByDescending(x => x.Email).ToArray();
                break;
            case "Phone":
                stdMaster = stdMaster.OrderByDescending(x => x.Phone).ToArray();
                break;
            case "Address":
                stdMaster = stdMaster.OrderByDescending(x => x.Address).ToArray();
                break;
        }
    }
}

Filtering Method

In each column heading part we have added a new row for performing the Filtering of the HTML grid. In each column filter Textbox Change event we pass the Textbox value. We call a common filtering method, studentFilteringList, and in this method, we pass the filtering column Textbox value and column Name.

// For Filtering by Student Name
void OnstdNameChanged(UIChangeEventArgs args)
{
    string values = args.Value.ToString();
    studentFilteringList(values, "StudentName");
}


// For Filtering by Email
void OnEmailChanged(UIChangeEventArgs args)
{
    string values = args.Value.ToString();
    studentFilteringList(values, "Email");
}


// For Filtering by Phone
void OnPhoneChanged(UIChangeEventArgs args)
{
    string values = args.Value.ToString();
    studentFilteringList(values, "Phone");
}


// For Filtering by Address
void OnAddressChanged(UIChangeEventArgs args)
{
    string values = args.Value.ToString();
    studentFilteringList(values, "Address");
}

Here, we create a common function named studentFilteringList and in this method, we get the filtering column Textbox value and column Name. We do filtering from the Web API and bind the filtering result to the HTML Table.

// Filtering
protected async Task studentFilteringList(String Value, string columnName)
{
    stdMaster = await Http.GetJsonAsync<StudentMasters[]>("/api/StudentMasters/");

    if (Value.Trim().Length > 0)
    {
        switch (columnName)
        {
            case "StudentName":
                stdMaster = stdMaster.Where(x => x.StdName.Contains(Value)).ToArray();
                break;

            case "Email":
                stdMaster = stdMaster.Where(x => x.Email.Contains(Value)).ToArray();
                break;
            case "Phone":
                stdMaster = stdMaster.Where(x => x.Phone.Contains(Value)).ToArray();
                break;
            case "Address":
                stdMaster = stdMaster.Where(x => x.Address.Contains(Value)).ToArray();
                break;
            default:
                stdMaster = await Http.GetJsonAsync<StudentMasters[]>("/api/StudentMasters/");
                break;
        }
    }
    else
    {
        stdMaster = await Http.GetJsonAsync<StudentMasters[]>("/api/StudentMasters/");
    }
}

Navigation Menu

Now, we need to add this newly added Student Razor page to our left Navigation. For adding this open the Shared Folder and open the NavMenu.cshtml page and add the menu.

<li class="nav-item px-3">
    <NavLink class="nav-link" href="/Students">
        <span class="oi oi-list-rich" aria-hidden="true"></span> Students Details
    </NavLink>
</li>

NavMenu.cshtml

Build and Run the application

Build and Run the application

Conclusion

Note that when creating the DBContext and setting the connection string, don’t forget to add your SQL connection string. Hope you all like this article and in the next article, we will see more examples of working with Blazor. It's really very cool and awesome to work with Blazor.