You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Blazor/Documentation/docusaurus/docs/view-data/blazorise-pagination.md

2.7 KiB

sidebar_position title
7 Blazorise pagination

Use pagination with Blazorise

Now that you have a functional grid, it is possible that your application returns a lot more data to you, in order to keep a fluid display, it is possible to set up pagination.

Add paging to grid

In order to set up pagination open the Pages/List.razor file and add the highlighted code to your page:

@page "/list"
@using Minecraft.Crafting.Models

<h3>List</h3>

<DataGrid TItem="Item"
          Data="@items"
// highlight-start
          ReadData="@OnReadData"
          TotalItems="@totalItem"
          PageSize="10"
          ShowPager
// highlight-end
          Responsive>
    <DataGridColumn TItem="Item" Field="@nameof(Item.Id)" Caption="#" />
    <DataGridColumn TItem="Item" Field="@nameof(Item.DisplayName)" Caption="Display name" />
    <DataGridColumn TItem="Item" Field="@nameof(Item.StackSize)" Caption="Stack size" />
    <DataGridColumn TItem="Item" Field="@nameof(Item.MaxDurability)" Caption="Maximum durability" />
    <DataGridColumn TItem="Item" Field="@nameof(Item.EnchantCategories)" Caption="Enchant categories">
        <DisplayTemplate>
            @(string.Join(", ", ((Item)context).EnchantCategories))
        </DisplayTemplate>
    </DataGridColumn>
    <DataGridColumn TItem="Item" Field="@nameof(Item.RepairWith)" Caption="Repair with">
        <DisplayTemplate>
            @(string.Join(", ", ((Item)context).RepairWith))
        </DisplayTemplate>
    </DataGridColumn>
    <DataGridColumn TItem="Item" Field="@nameof(Item.CreatedDate)" Caption="Created date" DisplayFormat="{0:d}" DisplayFormatProvider="@System.Globalization.CultureInfo.GetCultureInfo("fr-FR")" />
</DataGrid>

Add paging code

Open the Pages/List.razor.cs file and modify the code as follows:

public partial class List
{
	private List<Item> items;

	private int totalItem;

	[Inject]
	public HttpClient Http { get; set; }

	[Inject]
	public NavigationManager NavigationManager { get; set; }

	private async Task OnReadData(DataGridReadDataEventArgs<Item> e)
	{
		if (e.CancellationToken.IsCancellationRequested)
		{
			return;
		}

		// When you use a real API, we use this follow code
		//var response = await Http.GetJsonAsync<Item[]>( $"http://my-api/api/data?page={e.Page}&pageSize={e.PageSize}" );
		var response = (await Http.GetFromJsonAsync<Item[]>($"{NavigationManager.BaseUri}fake-data.json")).Skip((e.Page - 1) * e.PageSize).Take(e.PageSize).ToList();

		if (!e.CancellationToken.IsCancellationRequested)
		{
			totalItem = (await Http.GetFromJsonAsync<List<Item>>($"{NavigationManager.BaseUri}fake-data.json")).Count;
			items = new List<Item>(response); // an actual data for the current page
		}
	}
}