Back to Devexpress

DxPivotTable.LayoutAutoLoading Event

blazor-devexpress-dot-blazor-dot-pivottable-dot-dxpivottable-ba881d02.md

latest12.1 KB
Original Source

DxPivotTable.LayoutAutoLoading Event

Fires when the DxPivotTable component is initialized and starts to load its layout.

Namespace : DevExpress.Blazor.PivotTable

Assembly : DevExpress.Blazor.PivotTable.v25.2.dll

NuGet Package : DevExpress.Blazor.PivotTable

Declaration

csharp
[Parameter]
public Func<PivotTablePersistentLayoutEventArgs, Task> LayoutAutoLoading { get; set; }

Parameters

TypeDescription
PivotTablePersistentLayoutEventArgs

A PivotTablePersistentLayoutEventArgs object that defines data for this event.

|

Remarks

Handle the LayoutAutoLoading event to restore a Pivot Table layout when the component is initialized. The component starts loading the layout after the initial component state specified in the markup is applied. As an alternative, call the LoadLayout(PivotTablePersistentLayout) method to restore the layout on demand (for example, on a button click).

Use the PivotTable event argument and its members to obtain additional information about the Pivot Table. The Layout argument specifies the layout applied to the Pivot Table.

You can obtain an object that stores Pivot Table layout in one of the following ways:

You can use the following approach to implement different default layouts for mobile and desktop devices:

  • Save layouts to a database instead of browser storage in the LayoutAutoSaving event handler.
  • In the LayoutAutoLoading event handler, use the DxLayoutBreakpoint component to load the layout based on the screen size.

Example

The following code snippet demonstrates how to implement layout persistence for a Pivot Table. When layout changes, the LayoutAutoSaving event handler saves the updated layout to the browser’s local storage. Once the page is reloaded or restored, the LayoutAutoLoading event handler loads the most recently saved layout from the local storage and applies it to the Pivot Table.

razor
@using System.Text.Json
@inject NwindDataService NwindDataService
@inject IJSRuntime JSRuntime
<DxPivotTable @ref="@PivotTable"
              Data="@PivotData"
              VirtualScrollingEnabled="true"
              LayoutAutoLoading="PivotTable_LayoutAutoLoading"
              LayoutAutoSaving="PivotTable_LayoutAutoSaving">
    <Fields>
        <DxPivotTableField Field="SalesPerson" Area="PivotTableArea.Row" Caption="Sales Person" Width="270"/>
        <DxPivotTableField Field="ProductName" Area="PivotTableArea.Row" Caption="Product Name"/>
        <DxPivotTableField Field="ProductAmount" Area="PivotTableArea.Data" Caption="Product Amount" CellFormat="{0:c0}"/>
        <DxPivotTableField Field="Discount" Area="PivotTableArea.Data" CellFormat="{0:p0}"/>
        <DxPivotTableField Field="Country" AreaIndex="1"/>
        <DxPivotTableField Field="Region" AreaIndex="0"/>
        <DxPivotTableField Field="City" AreaIndex="-1"/>
        <DxPivotTableField Field="ExtendedPrice" AreaIndex="-1"/>
        <DxPivotTableField Field="OrderDate" GroupInterval="PivotTableGroupInterval.DateYear" Area="PivotTableArea.Column" Caption="Order Year" />
        <DxPivotTableField Field="OrderDate" GroupInterval="PivotTableGroupInterval.DateQuarter" Area="PivotTableArea.Column" Caption="Order Quater">
            <ValueTemplate>
                <span>@($"Q{context.Text}")</span>
            </ValueTemplate>
        </DxPivotTableField>
    </Fields>
</DxPivotTable>

@code {
    const string LocalStorageKey = "PivotTable-LayoutPersistence-Data";
    object PivotData { get; set; }
    IPivotTable PivotTable { get; set; }
    bool PreRendered { get; set; }
    protected override void OnAfterRender(bool firstRender) {
        if(firstRender) {
            PreRendered = true;
            StateHasChanged();
        }
    }
    protected override async Task OnInitializedAsync() {
        var invoices = await NwindDataService.GetInvoicesAsync();
        var customers = await NwindDataService.GetCustomersAsync();
        var minDate = invoices.Min(i => i.OrderDate).GetValueOrDefault();
        var maxDate = invoices.Max(i => i.OrderDate).GetValueOrDefault();
        PivotData = invoices.Where(i => {
            var invoiceDate = i.OrderDate.GetValueOrDefault();
            return invoiceDate.Year > minDate.Year && invoiceDate.Year <= maxDate.Year;
        }).Join(customers, i => i.CustomerId, c => c.CustomerId, (i, c) => {
            return new {
                CompanyName = c.CompanyName,
                UnitPrice = i.UnitPrice,
                OrderDate = i.OrderDate,
                ProductName = i.ProductName,
                ProductAmount = i.Quantity * i.UnitPrice,
                Country = c.Country,
                Region = c.Region,
                ExtendedPrice = i.ExtendedPrice,
                City = c.City,
                Discount = i.Discount,
                SalesPerson = i.Salesperson,
            };
        });
    }
    async Task PivotTable_LayoutAutoLoading(PivotTablePersistentLayoutEventArgs e) {
        e.Layout = await LoadLayoutFromLocalStorageAsync();
    }
    async Task PivotTable_LayoutAutoSaving(PivotTablePersistentLayoutEventArgs e) {
        await SaveLayoutToLocalStorageAsync(e.Layout);
    }
    // Refer to https://docs.microsoft.com/en-us/aspnet/core/blazor/state-management
    // to learn more about Blazor state management
    // In Blazor Server apps, prefer ASP.NET Core Protected Browser Storage
    async Task<PivotTablePersistentLayout> LoadLayoutFromLocalStorageAsync() {
        try {
            var json = await JSRuntime.InvokeAsync<string>("localStorage.getItem", LocalStorageKey);
            return JsonSerializer.Deserialize<PivotTablePersistentLayout>(json);
        } catch {
            // Mute exceptions for the server prerender stage
            return null;
        }
    }
    async Task SaveLayoutToLocalStorageAsync(PivotTablePersistentLayout layout) {
        try {
            var json = JsonSerializer.Serialize(layout);
            await JSRuntime.InvokeVoidAsync("localStorage.setItem", LocalStorageKey, json);
        } catch {
            // Mute exceptions for the server prerender stage
        }
    }
    async Task RemoveLayoutFromLocalStorageAsync() {
        try {
            await JSRuntime.InvokeVoidAsync("localStorage.removeItem", LocalStorageKey);
        } catch {
            // Mute exceptions for the server prerender stage
        }
    }
    async Task ReloadPageButton_ClickAsync() {
        await JSRuntime.InvokeVoidAsync("location.reload");
    }
    async Task ResetLayoutButton_ClickAsync() {
        await RemoveLayoutFromLocalStorageAsync();
        await JSRuntime.InvokeVoidAsync("location.reload");
    }
    void FieldListButton_Click() {
        PivotTable.ShowFieldList();
    }
}
csharp
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

namespace BlazorDemo.Data.Northwind {
    public class Invoice {
        public string ShipName { get; set; }
        public string ShipAddress { get; set; }
        public string ShipCity { get; set; }
        public string ShipRegion { get; set; }
        public string ShipPostalCode { get; set; }
        public string ShipCountry { get; set; }
        public string CustomerId { get; set; }
        public string CustomerName { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string Region { get; set; }
        public string PostalCode { get; set; }
        public string Country { get; set; }
        public string Salesperson { get; set; }
        public int OrderId { get; set; }
        public DateTime? OrderDate { get; set; }
        public DateTime? RequiredDate { get; set; }
        public DateTime? ShippedDate { get; set; }
        public string ShipperName { get; set; }
        public int ProductId { get; set; }
        public string ProductName { get; set; }
        public decimal UnitPrice { get; set; }
        public short Quantity { get; set; }
        public float Discount { get; set; }
        public decimal? ExtendedPrice { get; set; }
        public decimal? Freight { get; set; }
    }
}
csharp
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

namespace BlazorDemo.Data.Northwind {
    public partial class Customer {
        public Customer() {
            Orders = new HashSet<Order>();
        }

        public string CustomerId { get; set; }
        public string CompanyName { get; set; }
        public string ContactName { get; set; }
        public string ContactTitle { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string Region { get; set; }
        public string PostalCode { get; set; }
        public string Country { get; set; }
        public string Phone { get; set; }
        public string Fax { get; set; }

        public virtual ICollection<Order> Orders { get; set; }
    }
}
csharp
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BlazorDemo.Data.Northwind;
using BlazorDemo.DataProviders;

namespace BlazorDemo.Services {
    public partial class NwindDataService {
        public Task<IEnumerable<Invoice>> GetInvoicesAsync(CancellationToken ct = default) {
            // Return your data here
        }
    }
}
csharp
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BlazorDemo.Data.Northwind;
using BlazorDemo.DataProviders;

namespace BlazorDemo.Services {
    public partial class NwindDataService {
        public Task<IEnumerable<Customer>> GetCustomersAsync(CancellationToken ct = default) {
            // Return your data here
        }
    }
}
csharp
// ...
builder.Services.AddScoped<NwindDataService>();

Run Demo: Save and Restore the Layout

See Also

DxPivotTable Class

DxPivotTable Members

DevExpress.Blazor.PivotTable Namespace