Blazor Grid Remote Data Operations

    De forma predeterminada, utiliza IgbGrid su propia lógica para realizar operaciones de datos.

    Puede realizar estas tareas de forma remota y alimentar los datos resultantes a la IgbGrid aprovechando ciertas entradas y eventos, que son expuestos por el IgbGrid.

    Scroll infinito

    Un diseño popular para escenarios que requieren la obtención de datos por fragmentos de un punto final es el llamado desplazamiento infinito. En el caso de las cuadrículas de datos, se caracteriza por un aumento continuo de los datos cargados que se desencadena cuando el usuario final se desplaza hasta el final. En los siguientes párrafos se explica cómo puede usar la API disponible para lograr fácilmente un desplazamiento IgbGrid infinito.

    Para implementar el desplazamiento infinito, debes recuperar los datos en fragmentos. Los datos que ya se han obtenido deben almacenarse localmente y hay que determinar la longitud de un fragmento y cuántos fragmentos hay. También debe realizar un seguimiento del último índice de fila de datos visible en la cuadrícula. De esta manera, utilizando las propiedades StartIndex y ChunkSize, puede determinar si el usuario se desplaza hacia arriba y debe mostrarle los datos ya obtenidos o si se desplaza hacia abajo y debe obtener más datos desde el punto final.

    Lo primero que hay que hacer es obtener el primer fragmento de los datos. Establecer la propiedad es importante, ya que permite que la TotalItemCount cuadrícula ajuste el tamaño correcto de su barra de desplazamiento.

    @code {
            protected override async Task OnAfterRenderAsync(bool firstRender)
            {
                if (firstRender)
                {
                    var grid = this.grid;
                    grid.IsLoading = true;
                    double dataViewSize = 480.0 / 50.0;
                    this.PageSize = Convert.ToInt32(Math.Floor(dataViewSize * 1.5));
                    var data = await GetDataRemote(1, this.PageSize);
                    this.CachedData = data;
                    this.LocalData = this.CachedData;
                    grid.TotalItemCount = (this.PageSize * this.Page) + 1;
                    double pageCount = Math.Ceiling((double)this.TotalItems / (double)this.PageSize);
                    this.TotalPageCount = (int)pageCount;
                    grid.IsLoading = false;
                    StateHasChanged();
                }
    
            }
    }
    razor

    Además, debe suscribirse a la salida, de modo que pueda proporcionar los datos que necesita la DataPreLoad cuadrícula cuando intenta mostrar un fragmento diferente, en lugar del cargado actualmente. En el controlador de eventos, debe determinar si desea capturar nuevos datos o devolver datos que ya están almacenados en caché localmente.

    <IgbGrid AutoGenerate="false"
             Height="480px"
             Name="grid"
             Id="grid"
             Data="LocalData"
             @ref="grid"
             DataPreLoad="OnDataPreLoad">
        <IgbColumn Name="ID"
                   Field="ProductID"
                   Header="ID">
        </IgbColumn>
    
        <IgbColumn Name="ProductName"
                   Field="ProductName"
                   Header="Product Name">
        </IgbColumn>
    
        <IgbColumn Name="QuantityPerUnit"
                   Field="QuantityPerUnit"
                   Header="Quantity Per Unit">
        </IgbColumn>
    
        <IgbColumn Name="UnitPrice"
                   Field="UnitPrice"
                   Header="Unit Price">
        </IgbColumn>
    
        <IgbColumn Name="OrderDate"
                   Field="OrderDate"
                   Header="Order Date">
        </IgbColumn>
    
        <IgbColumn Name="Discontinued"
                   Field="Discontinued"
                   Header="Discontinued">
        </IgbColumn>
    
    </IgbGrid>
    @code {
            private IgbGrid grid;
            public async void OnDataPreLoad(IgbForOfStateEventArgs e)
            {
                int chunkSize = (int)e.Detail.ChunkSize;
                int startIndex = (int)e.Detail.StartIndex;
                int totalCount = (int)this.grid.TotalItemCount;
    
                bool isLastChunk = totalCount == startIndex + chunkSize;
                // when last chunk reached load another page of data
                if (isLastChunk)
                {
                    if (this.TotalPageCount == this.Page)
                    {
                        this.LocalData = this.CachedData.Skip(startIndex).Take(chunkSize).ToList();
                        return;
                    }
    
                    // add next page of remote data to cache
                    this.grid.IsLoading = true;
                    this.Page++;
                    var remoteData = await GetDataRemote(this.Page, this.PageSize);
                    this.CachedData.AddRange(remoteData);
    
                    var data = this.CachedData.Skip(startIndex).Take(chunkSize);
                    this.LocalData = data.ToList();
                    this.grid.IsLoading = false;
                    this.grid.TotalItemCount = Math.Min(this.Page * this.PageSize, this.TotalItems);
                }
                else
                {
                    var data = this.CachedData.Skip(startIndex).Take(chunkSize).ToList();
                    this.LocalData = data;
                }
            }
    }
    razor

    Demostración de desplazamiento infinito

    EXAMPLE
    DATA
    MODULES
    RAZOR
    CSS

    ¿Te gusta esta muestra? Obtenga acceso a nuestro kit de herramientas de Ignite UI for Blazor completo y comience a crear sus propias aplicaciones en minutos. Descárgalo gratis.

    Remote Paging

    The paging feature can operate with remote data. In order to demonstrate this let's first declare our service that will be responsible for data fetching. We will need the count of all data items in order to calculate the page count. This logic will be added to our service.

    As Blazor Server is already a remote instance, unlike the demos in the other platforms we do not need to set another remote instance for the data, as the data is already remote. In order to do remote paging, we just need to set a couple of methods ins the data class

            public Task<List<NwindDataItem>> GetData(int index, int perPage)
            {
                var itemsToReturn = items.Skip(index).Take(perPage).ToList();
                return Task.FromResult(itemsToReturn);
            }
    
            public Task<int> GetDataLength()
            {
                return Task.FromResult(items.Count);
            }
    razor

    After declaring the service, we need to create a component, which will be responsible for the IgbGrid construction and data subscription.

    First we should load some data to the grid. It is best to do after the grid has been rendered to avoid any timing issues.

        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
            {
                await Paginate(0, PerPage);
                totalRecordsCount = await NwindDataService.GetDataLength();
                StateHasChanged();
            }
        }
    razor

    After that we just need to bind the paging events to our custom methods, and remote paging is set:

    <IgbPaginator @ref="pager" PageChange="OnPageChange" PerPageChange="OnPerPageChange" TotalRecords="totalRecordsCount"></IgbPaginator>
    
    ....
    
    @code {
            private async void OnPerPageChange(IgbNumberEventArgs e)
        {
            PerPage = e.Detail;
            await Paginate(0, e.Detail);
        }
    
        private async void OnPageChange(IgbNumberEventArgs e)
        {
            await Paginate(e.Detail, PerPage);
        }
        ...
            private async Task Paginate(double page, double perPage)
        {
            this.page = page;
            double skip = this.page * PerPage;
            double top = PerPage;
    
            try
            {
                data = await NwindDataService.GetData(Convert.ToInt32(skip), Convert.ToInt32(perPage));
                isLoading = false;
                UpdateUI();
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine($"Error fetching data: {ex.Message}");
            }
        }
    }
    razor

    For further reference please check the full demo bellow:

    Grid Remote Paging Demo

    EXAMPLE
    DATA
    MODULES
    RAZOR
    CSS

    Problemas conocidos y limitaciones

    • Cuando la grilla no tiene PrimaryKey configurada y los escenarios de datos remotos están habilitados (al paginar, ordenar, filtrar y desplazar solicitudes de activación a un servidor remoto para recuperar los datos que se mostrarán en la grilla), una fila perderá el siguiente estado después de un dato. solicitud completa:
    • Selección de fila
    • Fila Expandir/contraer
    • Edición de filas
    • Fijación de filas

    Referencias de API

    Recursos adicionales

    Nuestra comunidad es activa y siempre da la bienvenida a nuevas ideas.