受欢迎的博客标签

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.

Date Temp. (C) Temp. (F) Summary
2020/3/27 53 127 Freezing
2020/3/28 8 46 Balmy
2020/3/29 12 53 Freezing
2020/3/30 -17 2 Scorching
2020/3/31 48 118 Chilly

BlazorGrid

Date TemperatureC TemperatureF Summary
2020/3/27 53 127 Freezing
2020/3/28 8 46 Balmy
2020/3/29 12 53 Freezing
2020/3/30 -17 2 Scorching