Completed
Last Updated: 22 Feb 2024 13:31 by ADMIN
Release 2024 Q2 (May)
David
Created on: 22 Feb 2023 12:31
Category: Grid
Type: Bug Report
7
Wrong aggregates on initial load with OnRead binding

When the Grid is databound via OnRead event, the initially displayed aggregates are wrong and take into account the first page only.

A possible workaround is to bind the Grid in OnAfterRenderAsync -

@using Telerik.DataSource
@using Telerik.DataSource.Extensions

<TelerikGrid @ref="@GridRef"
             OnRead="@OnGridRead"
             TItem="@Product"
             Pageable="true">
    <GridAggregates>
        <GridAggregate Field="@nameof(Product.Name)" Aggregate="@GridAggregateType.Count" FieldType="@(typeof(System.String))" />
    </GridAggregates>
    <GridColumns>
        <GridColumn Field="@nameof(Product.Name)" Title="Product Name">
            <FooterTemplate>
                @context.Count
            </FooterTemplate>
        </GridColumn>
        <GridColumn Field="@nameof(Product.Price)" />
        <GridColumn Field="@nameof(Product.ReleaseDate)" Title="Release Date" />
        <GridColumn Field="@nameof(Product.Active)" />
    </GridColumns>
</TelerikGrid>

@code {
    TelerikGrid<Product> GridRef { get; set; }
    List<Product> GridData { get; set; }

    bool ShouldBindGrid { get; set; }

    async Task OnGridRead(GridReadEventArgs args)
    {
        if (!ShouldBindGrid)
        {
            return;
        }

        await Task.Delay(200); // simulate network delay

        DataSourceResult result = GridData.ToDataSourceResult(args.Request);

        args.Data = result.Data;
        args.Total = result.Total;
        args.AggregateResults = result.AggregateResults;
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            // workaround for initial Grid aggregates
            ShouldBindGrid = true;
            GridRef.Rebind();
            StateHasChanged();
        }
    }

    protected override void OnInitialized()
    {
        GridData = new List<Product>();
        var rnd = new Random();

        for (int i = 1; i <= 50; i++)
        {
            GridData.Add(new Product()
            {
                Id = i,
                Name = "Product " + i.ToString(),
                Price = (decimal)rnd.Next(1, 100),
                ReleaseDate = DateTime.Now.AddDays(-rnd.Next(60, 1000)),
                Active = i % 3 == 0
            });
        }
    }

    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public DateTime ReleaseDate { get; set; }
        public bool Active { get; set; }
    }
}

0 comments