Creating A Reusable Grid Component For Blazor

In this article, we will create a reusable grid component for Blazor called BlazorGrid. It will display the user data in a grid and supports client-side pagination.

Introduction

 
In this article, we will create a reusable grid component for Blazor called BlazorGrid. It will display the user data in a grid and will support the client-side pagination.
 
Take a look at the final application.
 
Creating BlazorGrid
 
Since this is a reusable component, we will also publish it to nuget.org as a NuGet package. To learn how to publish BlazorGrid component to a NuGet gallery, refer to my article Blazor - Publishing A Component To NuGet Gallery.
 
Prerequisites
  • Install the .NET Core 2.1 or above SDK from here
  • Install the latest version of Visual Studio 2017 from here
  • Install ASP.NET Core Blazor Language Services extension from here
  • Install Blazor templates on the command-line using the following command.
  1. dotnet new -i Microsoft.AspNetCore.Blazor.Templates  
Source Code
 
Get the source code from GitHub.
 

Creating Blazor Library project

 
To create a Blazor library project, follow the steps mentioned below:
  1. Navigate to the folder where you want to create your project.
  2. Open command prompt or Windows PowerShell as administrator.
  3. Run the following command:
  1. dotnet new blazorlib -o BlazorGridComponent  
It will create a Blazor library project with the name BlazorGridComponent.
 
Open this project using Visual Studio. You will see a folder structure as shown in the image below.
 
Creating BlazorGrid
 
There are some predefined files provided in this project. We will delete Component1.cshtml, ExampleJsInterop.cs, exampleJsInterop.js, and background.png files to make our solution clean. Do not delete styles.css as we will put the CSS definitions for our custom component in this file.
 

Creating BlazorGrid component

 
Now, we will add the component view page to our project.
 
Right-click on the BlazorGridComponent project and then select Add >> New Item. An “Add New Item” dialog box will open; select “Web” from the left panel, then select “Razor View” from templates panel, and name it BlazorGrid.cshtml. Click Add. Refer to the image below.
 
Creating BlazorGrid 
 
Open the BlazorGrid.cshtml file and put the following code into it.
  1. @typeparam TableItem  
  2.   
  3. <table>  
  4.     <thead>  
  5.         <tr class="jsgrid-grid-header">@GridHeader</tr>  
  6.     </thead>  
  7.     <tbody>  
  8.         @foreach (var item in ItemList)  
  9.         {  
  10.             <tr class="jsgrid-row-item">@GridRow(item)</tr>  
  11.         }  
  12.     </tbody>  
  13. </table>  
  14. <div class="pagination">  
  15.   
  16.     <button class="btn pagebutton btn-info" onclick=@(async () => SetPagerSize("back"))>«</button>  
  17.     <button class="btn pagebutton btn-secondary" onclick=@(async () => NavigateToPage("previous"))>Prev</button>  
  18.   
  19.     @for (int i = startPage; i <= endPage; i++)  
  20.     {  
  21.         var currentPage = i;  
  22.         <button class="btn pagebutton @(currentPage==curPage?"currentpage":"")" onclick=@(async () => updateList(currentPage))>  
  23.             @currentPage  
  24.         </button>  
  25.     }  
  26.   
  27.     <button class="btn pagebutton btn-secondary" onclick=@(async () => NavigateToPage("next"))>Next</button>  
  28.     <button class="btn pagebutton btn-info" onclick=@(async () => SetPagerSize("forward"))>»</button>  
  29.   
  30.     <span class="pagebutton btn btn-link disabled">Page @curPage of @totalPages</span>  
  31.   
  32. </div>  
  33.   
  34. @functions {  
  35. int totalPages;  
  36. int curPage;  
  37. int pagerSize;  
  38. int startPage;  
  39. int endPage;  
  40.   
  41. [Parameter]  
  42. RenderFragment GridHeader { getset; }  
  43. [Parameter]  
  44. RenderFragment<TableItem> GridRow { getset; }  
  45. [Parameter]  
  46. IEnumerable<TableItem> Items { getset; }  
  47. [Parameter]  
  48. int PageSize { getset; }  
  49.   
  50. IEnumerable<TableItem> ItemList { getset; }  
  51.   
  52. protected override async Task OnInitAsync()  
  53. {  
  54.     pagerSize = 5;  
  55.     curPage = 1;  
  56.   
  57.     ItemList = Items.Skip((curPage - 1) * PageSize).Take(PageSize);  
  58.     totalPages = (int)Math.Ceiling(Items.Count() / (decimal)PageSize);  
  59.   
  60.     SetPagerSize("forward");  
  61. }  
  62.   
  63. public void updateList(int currentPage)  
  64. {  
  65.     ItemList = Items.Skip((currentPage - 1) * PageSize).Take(PageSize);  
  66.     curPage = currentPage;  
  67.     this.StateHasChanged();  
  68. }  
  69.   
  70. public void SetPagerSize(string direction)  
  71. {  
  72.     if (direction == "forward" && endPage < totalPages)  
  73.     {  
  74.         startPage = endPage + 1;  
  75.         if (endPage + pagerSize < totalPages)  
  76.         {  
  77.             endPage = startPage + pagerSize - 1;  
  78.         }  
  79.         else  
  80.         {  
  81.             endPage = totalPages;  
  82.         }  
  83.         this.StateHasChanged();  
  84.     }  
  85.     else if (direction == "back" && startPage > 1)  
  86.     {  
  87.         endPage = startPage - 1;  
  88.         startPage = startPage - pagerSize;  
  89.     }  
  90. }  
  91.   
  92. public void NavigateToPage(string direction)  
  93. {  
  94.     if (direction == "next")  
  95.     {  
  96.         if (curPage < totalPages)  
  97.         {  
  98.             if (curPage == endPage)  
  99.             {  
  100.                 SetPagerSize("forward");  
  101.             }  
  102.             curPage += 1;  
  103.         }  
  104.     }  
  105.     else if (direction == "previous")  
  106.     {  
  107.         if (curPage > 1)  
  108.         {  
  109.             if (curPage == startPage)  
  110.             {  
  111.                 SetPagerSize("back");  
  112.             }  
  113.             curPage -= 1;  
  114.         }  
  115.     }  
  116.     updateList(curPage);  
  117. }  
  118. }  
Let’s understand this code.
 
In the HTML section of the code, we have defined a table. The <thead> section of the table will display the header of the grid as defined in GridHeader parameter. Similarly, the <tbody> section will iterate through the content of GridRow parameter to display the data in rows.
 
We have also defined the HTML of pagination section. It contains Next and Prev buttons to move through the pages. We have also defined the buttons to navigate to the next set of pages. The default pager size is set to five. This means the page buttons will be displayed in a set of five buttons.
 
In the functions section, we have defined four parameters for BlazorGrid component:
  • Items: The list of items supplied to the BlazorGrid.
  • PageSize: Size of each page of BlazorGrid.
  • GridHeader: Header for BlazorGrid.
  • GridRow: Rows for BlazorGrid.
Inside the OnInitAsync method, we are initializing the pagerSize to five and setting the curPage to one. We will calculate the total number of pages and bind the data to the first page of the grid.
 
The updateList method will be invoked when we click on a page button. It will bind the data to the current page of the grid.
 
The SetPagerSize method will set the page number in every pager set. The page buttons will be displayed in a set of five buttons and if the number of pages is more than five, the page button will be displayed in the next pager set. This method will accept a string parameter and based on the value it will set the page buttons for next or previous set of five buttons. A demo of pager set is shown below.
 
Creating BlazorGrid 
 
The NavigateToPage method will be invoked on clicking the Next or Prev button. It will navigate the user to immediate next or immediate previous page in the grid.
 

Adding CSS for BlazorGrid component

 
Open "/content/styles.css" file and put the following code into it.
  1. .jsgrid-grid-header {  
  2.     text-aligncenter;  
  3.     border-collapsecollapse;  
  4.     background#ebebeb;  
  5. }  
  6.   
  7. .jsgrid-row-item:hover {  
  8.     background#9fcdf4;  
  9. }  
  10.   
  11. th, td {  
  12.     padding15px;  
  13.     border1px solid #d1d1d1;  
  14.     text-aligncenter;  
  15. }  
  16.   
  17. .pagebutton {  
  18.     margin-right5px;  
  19.     margin-top5px;  
  20. }  
  21.   
  22. .currentpage {  
  23.     background-color: dodgerblue;  
  24.     colorwhite;  
  25. }  
In this file, we have defined styling for BlazorGrid component. Now, we will use this component in a Blazor project.
 

Create Blazor Web Application

 
Open Visual Studio and select File >> New >> Project.
 
After selecting the project, a “New Project” dialog will open. Select .NET Core inside the Visual C# menu from the left panel. Then, select “ASP.NET Core Web Application” from available project types. Put the name of the project as TestApplication and press OK.
 
After clicking on OK, a new dialog will open asking you to select the project template. You can observe two drop-down menus at the top left of the template window. Select “.NET Core” and “ASP.NET Core 2.1” from these dropdowns. Then, select “Blazor” template and press OK. Refer to the image below:
 
Creating BlazorGrid 
 

Adding the BlazorGrid component to the Blazor project

 
To include the BlazorGridComponent project in this Blazor project, follow the steps mentioned below:
  1. Right-click on the solution and select Add >> Existing item.
  2. Browse to the BlazorGridComponent library, select the BlazorGridComponent.csproj file, and click Add.
This will include the BlazorGridComponent project in the current solution. Refer to the image below.
 
Creating BlazorGrid 
 
The next step is to add the reference to the shared component. Right-click “TestApplication\Dependencies”. Select "Add Reference..." Then, select BlazorGridComponent project and click OK. Refer to the image below:
 
Creating BlazorGrid 
 
The final step is to add the following line to "TestApplication\ _ViewImports.cshtml" file.
  1. @addTagHelper *,BlazorGridComponent  
This will allow us to use the shared BlazorGridComponent in our TestApplication project.
 

Using BlazorGrid component

 
Open "TestApplication\Pages\FetchData.cshtml" file. In the HTML section of the code put the following lines inside the else section.
  1. <BlazorGrid Items="@forecasts" PageSize="4">  
  2.     <GridHeader>  
  3.         <th>Date</th>  
  4.         <th>TemperatureC</th>  
  5.         <th>TemperatureF</th>  
  6.         <th>Summary</th>  
  7.     </GridHeader>  
  8.     <GridRow>  
  9.         <td>@context.Date.ToShortDateString()</td>  
  10.         <td>@context.TemperatureC</td>  
  11.         <td>@context.TemperatureF</td>  
  12.         <td>@context.Summary</td>  
  13.     </GridRow>  
  14. </BlazorGrid>  
The name of HTML tag will be the same as the file name of our component, which is <BlazorGrid> in this case. We are setting the value of Items parameter to forecasts. We have set the PageSize to 4 which means the grid will display four items in each page. The headers for the Grid are defined in <GridHeader>.
 
Inside the <GridRow> we have declared the row items for our grid using the implicit parameter “context”. The Blazor framework provides this and we need to use it to initialize the arguments of type RenderFragment<T>, which is GridRow in this case.
 
Execution Demo
 
Run the application and navigate to the Fetch data page. You will see the data is being displayed in a Grid fashion as shown in the image below:
 
Creating BlazorGrid 
 

Conclusion

 
We have created a shared Blazor component – BlazorGrid. It displays the user data in a grid. This component also provides client-side pagination. We learned how to reference and use the shared component in a Blazor application.
Get the source code from GitHub and play around to get a better understanding.
 
You can also read my other articles at my blog here
 
See Also