blazorblazor-webassemblymudblazor

MudBlazor Data Grid show index with arrow when persist data


I'm using MudBlazor's Data Grid and I'm implementing a method to save the search, sort, and pagination status. When you leave the page and return, the table displays the last search, sort, and pagination you modified.

Everything works correctly except for part of the sorting.

When one of the columns is sorted, an arrow appears with a number next to it.

enter image description here

When I leave the page and return, everything displays the previous version as I modified it, with the arrow indicating the sort order, but the number is not displayed.

enter image description here

How can I get that number to appear?

My code is as follows

<MudDataGrid T="Model"              
@ref="_grid"              
LoadingProgressColor="Color.Primary"
Virtualize="false"      
ServerData="ServerDataFunc"              
RowClick="HandleRowDoubleClick" 
MultiSelection="true"  
CurrentPage="GridStateService.State.Page"
RowsPerPage="GridStateService.State.PageSize"              
Filterable="true"
SortDefinitions="GridStateService.State.SortDefinitionsBind" 
@bind-SelectedItems="SelectedModel"> 

public class GridState<T> 
{     
    public int Page { get; set; } = 0;     
    public int PageSize { get; set; } = 10;     
    public string? SearchText { get; set; }        
    public ICollection<SortDefinition<T>>? SortDefinitions { get; set; }     
    public ICollection<IFilterDefinition<T>>? FilterDefinitions { get; set; }   
    public HashSet<T> SelectedItems { get; set; } = new();        
    public Dictionary<string, SortDefinition<T>> SortDefinitionsBind     
    {         
        get => SortDefinitions?.Where( x => !string.IsNullOrWhiteSpace( x.SortBy ) ).ToDictionary(x => x.SortBy, x => x) ?? new();
        set {
            SortDefinitions = value?.Values.ToList() ?? new List<SortDefinition<T>>();                   }
     } 
}

Solution

  • You can use MudDataGrid.ExtendSortAsync.

    From the docs

    Adds or replaces a sort behavior depending on the SortMode . When the SortMode is Single , this method replaces the sort column. Otherwise, this sort is appended to any existing sort column.

    And, whatever property you push first gets sort order ⬆ 1

    private MudDataGrid<Item> DataGrid;
    
    protected override async Task OnAfterRenderAsync(bool firstRender) {
      if (firstRender) {
        await DataGrid.ExtendSortAsync(nameof(Item.Value), SortDirection.Ascending, x => x.Value, NaturalSortingEnabled ? new MudBlazor.Utilities.NaturalComparer() : null);
        await DataGrid.ExtendSortAsync(nameof(Item.Name), SortDirection.Ascending, x => x.Name, NaturalSortingEnabled ? new MudBlazor.Utilities.NaturalComparer() : null);
        await InvokeAsync(StateHasChanged);
      }
    }
    

    TryMudblazor Snippet

    enter image description here