How to use Multiselection with MudSelect in Mudblazor

764 Views Asked by At

I am creating a UI which takes user details from database and display it in mudtable with columns userid,email,groupof(contains comma separated value eg. scteam,mgteam,trteam)from usertable .I am creating multiselect for each groupof field in mudtable .When security admin want to add or remove a user from the group, they can select that and click save button .The changes should be made in database. In the below code I can select values but I couldn't save it if I use only SelectedValues and if I use only @bind-Value I cant give more than one default value and if I use both, my program crashes .How to solve this?

This is what I tried

  <RowTemplate>
    <MudTd DataLabel="UserId">@context.UserId</MudTd>

    <MudTd DataLabel="Email">@context.Email</MudTd>

    <MudTd DataLabel="SEGroupOf">
        <MudSelect T="string" MultiSelection="true" @bind-Value="@context.SegroupOf" SelectedValues="@SelectValues(context.SegroupOf)" AnchorOrigin="Origin.BottomCenter">

                @foreach (var group in SEGroup)
                {
                    <MudSelectItem T="string" Value="@group">@group</MudSelectItem>
                }
            </MudSelect>
    
    </MudTd>

    <MudTd DataLabel="SEGroupOf">
        <MudButton ButtonType="ButtonType.Submit" Variant="Variant.Filled" Color="Color.Primary" @onclick="@(()=>SaveSelectedGroups(@context))">Save</MudButton>

    </MudTd>
    
</RowTemplate>


public IEnumerable<string> SelectValues(string segroupOf)
{
    selectedGroups = segroupOf.Split(',').ToList();
    return selectedGroups;
}

Thank you!!!

This is my code snippet

1

There are 1 best solutions below

0
On BEST ANSWER

You can remove the @bind-Value and only use SelectedValues and SelectedValuesChanged.

In the code below, we convert the string to an array (while filtering out empty strings) as SelectedValues expects an IEnumerable<T> and by using the SelectedValuesChanged we handle the changing of the selections directly in the context model itself.

<MudSelect T="string" MultiSelection="true" AnchorOrigin="Origin.BottomCenter"
    SelectedValues="@(context.SegroupOf.Split(',').Where(x => !string.IsNullOrEmpty(x)))"
    SelectedValuesChanged="@(x=>HandleSelectedValuesChanged(x,context))">
    @foreach (var group in SEGroup)
    {
    <MudSelectItem T="string" Value="@group">@group</MudSelectItem>
    }
</MudSelect>

@code{
    private void HandleSelectedValuesChanged(IEnumerable <string> changedValues, UserTable userTable)
    {
        userTable.SegroupOf = string.Join(",", changedValues);
    }
}

MudBlazor Snippet