Popular blog tags

ASP.NET Core Blazor UI components series(6):Creating a Reusable Custom Table blazor Components step by step(blazorgrid)

Published

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.

 

 

.Net 6.x

Creating Blazor Library project

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” from templates panel, and name it BlazorGrid.razor. Click Add. Refer to the image below.




<h3>BlazorGrid</h3>


@typeparam TableItem

<table class="table">
    <thead>
        <tr class="jsgrid-grid-header">@GridHeader</tr>
    </thead>
    <tbody>
        @foreach (var item in ItemList)
        {
            <tr class="jsgrid-row-item">@GridRow(item)</tr>
        }
    </tbody>
</table>

<div class="pagination">

    <button class="btn pagebutton btn-info" onclick=@(async () => SetPagerSize("back"))>«</button>
    <button class="btn pagebutton btn-secondary" onclick=@(async () => NavigateToPage("previous"))>Prev</button>

    @for (int i = startPage; i <= endPage; i++)
    {
        var currentPage = i;
        <button class="btn pagebutton @(currentPage==curPage?"currentpage":"")" onclick=@(async () => updateList(currentPage))>
            @currentPage
        </button>
    }

    <button class="btn pagebutton btn-secondary" onclick=@(async () => NavigateToPage("next"))>Next</button>
    <button class="btn pagebutton btn-info" onclick=@(async () => SetPagerSize("forward"))>»</button>

    <span class="pagebutton btn btn-link disabled">Page @curPage of @totalPages</span>

</div>






@code {
    int totalPages;
    int curPage;
    int pagerSize;
    int startPage;
    int endPage;



    [Parameter]
    public RenderFragment GridHeader { get; set; }

    [Parameter]
    public RenderFragment<TableItem> GridRow { get; set; }

    [Parameter]
    public IEnumerable<TableItem> Items { get; set; }

    [Parameter]
    public int PageSize { get; set; }

    [Parameter]
    public IEnumerable<TableItem> ItemList { get; set; }

    protected override async Task OnInitializedAsync()
    {
        pagerSize = 5;
        curPage = 1;

        ItemList = Items.Skip((curPage - 1) * PageSize).Take(PageSize);
        totalPages = (int)Math.Ceiling(Items.Count() / (decimal)PageSize);

        SetPagerSize("forward");
    }

    public void updateList(int currentPage)
    {
        ItemList = Items.Skip((currentPage - 1) * PageSize).Take(PageSize);
        curPage = currentPage;
        this.StateHasChanged();
    }

    public void SetPagerSize(string direction)
    {
        if (direction == "forward" && endPage < totalPages)
        {
            startPage = endPage + 1;
            if (endPage + pagerSize < totalPages)
            {
                endPage = startPage + pagerSize - 1;
            }
            else
            {
                endPage = totalPages;
            }
            this.StateHasChanged();
        }
        else if (direction == "back" && startPage > 1)
        {
            endPage = startPage - 1;
            startPage = startPage - pagerSize;
        }
    }

    public void NavigateToPage(string direction)
    {
        if (direction == "next")
        {
            if (curPage < totalPages)
            {
                if (curPage == endPage)
                {
                    SetPagerSize("forward");
                }
                curPage += 1;
            }
        }
        else if (direction == "previous")
        {
            if (curPage > 1)
            {
                if (curPage == startPage)
                {
                    SetPagerSize("back");
                }
                curPage -= 1;
            }
        }
        updateList(curPage);
    }
}

 

Create Blazor Server Web Application for test

Add Reference Razor Class Library project

Adding the BlazorGrid component to the Blazor project

Using BlazorGrid component 

Execution Demo 

 

 

.Net 5.x

Prerequisites


Here’s what you’ll need to use our Razor Class Library project with the Blazor framework:

Visual Studio 2019 with the ASP.NET and Web Development workload
.NET 5.0+ Framework

step 1:Create  a new Razor Class Library project

step 2:Create  a new Blazor Server Library project

source on github:https://github.com/iaspnetcore/iAspNetCore.RazorComponents/commit/7eeb63fdab78db8bae3ba68d1a2225e47697a288

 

Table.razor

https://docs.microsoft.com/en-us/aspnet/core/blazor/components/templated-components?view=aspnetcore-5.0

step 1:Create a Table component (Table.razor)

<h3>Table</h3>

@typeparam TItem

<table class="table">
    <thead>
        <tr>@TableHeader</tr>
    </thead>
    <tbody>
        @foreach (var item in Items)
        {
            <tr>@RowTemplate(item)</tr>
        }
    </tbody>
</table>

@code {
    [Parameter]
    public RenderFragment TableHeader { get; set; }

    [Parameter]
    public RenderFragment<TItem> RowTemplate { get; set; }

    [Parameter]
    public IReadOnlyList<TItem> Items { get; set; }
}

 

Step 2:Add Reference Razor Class Library project

 

Step 3:

@page "/fetchdata"

@using iAspNetCore.RazorComponents

@using BlazorServer.Data
@inject WeatherForecastService ForecastService

<h1>Table  Component Demo</h1>

<Table Items="forecasts">
    <TableHeader>
        <th>ID</th>
        <th>Name</th>
    </TableHeader>
    <RowTemplate>
        <td>@context.Date.ToShortDateString()</td>
        <td>@context.TemperatureC</td>
    </RowTemplate>
</Table>

outpiut

IDName
2021/2/1549
2021/2/1645
2021/2/17-1
2021/2/1829
2021/2/19-4

 

 

 

.Net core 3.x

https://dzone.com/articles/blazorgrid-a-reusable-grid-component-for-blazor

update 

current version: asp .net core 3.x  2020.03.26

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 supports client-side pagination.

Source Code

Get the source code from GitHub

Part one:Create  Razor Class Library project named with iAspNetCore.RazorComponents

step 1:Create new a new Razor Class Library project

From Visual Studio

From Visual Studio select Create new a new project.
Select Razor Class Library > Next.
Name the library (for example, "iAspNetCore.RazorComponents"), > Create. To avoid a file name collision with the generated view library, ensure the library name doesn't end in .Views.
Select Support pages and views if you need to support views. By default, only Razor Pages are supported. Select Create.

From the command line

Navigate to the folder where you want to create your project.
Open the command prompt or Windows PowerShell as an administrator.
Run the following command:

dotnet new razorclasslib -o iAspNetCore.RazorComponents

 

step 2:Creating a BlazorGrid Component

 

<h3>BlazorGrid</h3>
@using System.Threading.Tasks;

@typeparam TableItem

<table>
    <thead>
        <tr class="blazor-grid-header">@GridHeader</tr>
    </thead>
    <tbody>
        @foreach (var item in ItemList)
        {
            <tr class="blazor-row-item">@GridRow(item)</tr>
        }
    </tbody>
</table>
<div class="pagination">

    <button class="btn pagebutton btn-info" @onclick="@(e =>  SetPagerSize("back"))">&laquo;</button>
    <button class="btn pagebutton btn-secondary" @onclick="@(e => NavigateToPage("previous"))">Prev</button>


    @for (int i = startPage; i <= endPage; i++)
    {
        var currentPage = i;
        <button class="btn pagebutton @(currentPage==curPage?"currentpage":"")" @onclick="@(e => 
            updateList(currentPage))">
            @currentPage
        </button>
    }

    
    <button class="btn pagebutton btn-secondary" @onclick="@(e =>   NavigateToPage("next"))">Next</button>

    <button class="btn pagebutton btn-info" @onclick="@(e =>   SetPagerSize(" forward"))">&raquo;</button>

    <span class="pagebutton btn btn-link disabled">Page @curPage of @totalPages</span>

</div>

@code {
    int totalPages;
    int curPage;
    int pagerSize;

    int startPage;
    int endPage;

    /// <summary>
    /// Header for BlazorGrid.
    /// </summary>
    [Parameter]
    public RenderFragment GridHeader { get; set; }

    /// <summary>
    /// Rows for BlazorGrid.
    /// </summary>
    [Parameter]
    public RenderFragment<TableItem> GridRow { get; set; }

    /// <summary>
    /// The list of item supplied to the BlazorGrid.
    /// </summary>
    [Parameter]
    public IEnumerable<TableItem> Items { get; set; }

    /// <summary>
    /// Size of each page of BlazorGrid. This is a required field.
    /// </summary>
    [Parameter]
    public int PageSize { get; set; }

    IEnumerable<TableItem> ItemList { get; set; }


    protected override async Task OnInitializedAsync()
    {
        pagerSize = 5;
        curPage = 1;

        ItemList = Items.Skip((curPage - 1) * PageSize).Take(PageSize);
        totalPages = (int)Math.Ceiling(Items.Count() / (decimal)PageSize);

        SetPagerSize("forward");
    }

    public void updateList(int currentPage)
    {
        ItemList = Items.Skip((currentPage - 1) * PageSize).Take(PageSize);
        curPage = currentPage;
        this.StateHasChanged();
    }

    public async Task SetPagerSize(string direction)
    {
        if (direction == "forward" && endPage < totalPages)
        {
            startPage = endPage + 1;
            if (endPage + pagerSize < totalPages)
            {
                endPage = startPage + pagerSize - 1;
            }
            else
            {
                endPage = totalPages;
            }
            this.StateHasChanged();
        }
        else if (direction == "back" && startPage > 1)
        {
            endPage = startPage - 1;
            startPage = startPage - pagerSize;
        }
    }

    public void NavigateToPage(string direction)
    {
        if (direction == "next")
        {
            if (curPage < totalPages)
            {
                if (curPage == endPage)
                {
                    SetPagerSize("forward");
                }
                curPage += 1;
            }
        }
        else if (direction == "previous")
        {
            if (curPage > 1)
            {
                if (curPage == startPage)
                {
                    SetPagerSize("back");
                }
                curPage -= 1;
            }
        }

        updateList(curPage);
    }
}

 

Part two:using  iAspNetCore.RazorComponents  Razor Class Library project 

Demo in blazor server project

step 1:Create a Blazor server Web Application

step 2:Adding the BlazorGrid Component to the Blazor server Project

Select Add Reference... Then, select the BlazorGridComponent project and click OK

path:\src\demo\BlazorServer\BlazorServer.csproj

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <ProjectReference Include="..\..\libraries\iAspNetCore.RazorComponents\iAspNetCore.RazorComponents.csproj" />
  </ItemGroup>

</Project>

step3:Using the BlazorGrid Component

Open TestApplication\Pages\FetchData.cshtml file. In the HTML section of the code put the following lines inside the else section.

path:\src\demo\BlazorServer\Pages\FetchData.razor

@using iAspNetCore.RazorComponents
<BlazorGrid Items="@forecasts" PageSize="4">
    <GridHeader>
        <th>Date</th>
        <th>TemperatureC</th>
        <th>TemperatureF</th>
        <th>Summary</th>
    </GridHeader>
    <GridRow>
        <td>@context.Date.ToShortDateString()</td>
        <td>@context.TemperatureC</td>
        <td>@context.TemperatureF</td>
        <td>@context.Summary</td>
    </GridRow>
</BlazorGrid>

 

output

 

 

Create reusable UI using the Razor class library project in ASP.NET Core

 

Weather forecast

This component demonstrates fetching data from a service.

DateTemp. (C)Temp. (F)Summary
2020/3/2753127Freezing
2020/3/28846Balmy
2020/3/291253Freezing
2020/3/30-172Scorching
2020/3/3148118Chilly

BlazorGrid

DateTemperatureCTemperatureFSummary
2020/3/2753127Freezing
2020/3/28846Balmy
2020/3/291253Freezing
2020/3/30-172Scorching