datagridblazor-webassemblymudblazortwo-way-binding

MudDataGrid with multiple selection not working in two way, @bind-SelectedItems="selectedRoles"


I have this grid:

@if (collections != null && collections.Roles != null && 
    collections.Roles.Count() > 0 && selectedRoles != null)
        {
            <MudBlazor.MudDataGrid T="Role" MultiSelection="true"
                                   Items="@collections.Roles"
                                   @bind-SelectedItems="selectedRoles">
                <Columns>
                    <PropertyColumn Property="x => x.Name" Title="Caption"
                                    Style="width: 100px;" />
                    <MudBlazor.SelectColumn T="Role" ShowInFooter="false" />
                </Columns>
            </MudBlazor.MudDataGrid>
            }

the grid works when I select some items and click submit, correctly sending selectedItems.

But when the page first loads I do this:

HashSet<Role> selectedRoles = null;
 protected override async Task OnInitializedAsync()
 {
     await base.OnInitializedAsync();

     await GetPerson();
     selectedRoles = person.User.Roles.ToHashSet<Role>();    
     StateHasChanged();
 }

But when the page first loads no roles are selected in the datagrid, and there is items in the person.User.Roles.ToHashSet<Role>(); code, that the datagrid not showing.


Solution

  • I solve my problem using this code in oninitialized method:

    selectedRoles =  person.User.Roles.Select(r => 
         collections.Roles.First(r2 => r2.Id == r.Id)).ToHashSet<Role>();
    

    The roles should be the same object to be selected.