I have used a custom class with MudSelect. How do I get the list of selected items back?

200 Views Asked by At

I have populated the Mudselect with items from my custom class multiselectitem. When I hit the submit button I cannot retrive the list of selected items. How do I do this?

https://try.mudblazor.com/snippet/wamRlEPARwjQLTFn

`

@foreach (multiselectitem item in allitems) { }

Submit

@code { private List selectedtestitems = new List();

private List<multiselectitem> allitems = new() {
    new multiselectitem{id = 1, name = "test 1"},
    new multiselectitem{id = 2, name = "test 2"},
    new multiselectitem{id = 3, name = "test 3"},
    new multiselectitem{id = 4, name = "test 4"},
};

private string ToString(multiselectitem x)
    => x is null ? string.Empty : $"{x.name}";

public class multiselectitem
{
    public int id { get; set; }
    public string name { get; set; }
    public override bool Equals(object o)
    {
        var other = o as multiselectitem;
        return other?.id == id;
    }
    public override int GetHashCode() => id.GetHashCode();
}

public void ProcessTheList()
{
    foreach (var item in selectedtestitems)
    {
        Console.WriteLine(item.name);
    }
}

}`

1

There are 1 best solutions below

0
On BEST ANSWER

You can add a SelectedValuesChanged method and asign the values there:

private void SelectedValuesChanged(IEnumerable<multiselectitem> values)
{
    this.selectedtestitems = values.ToList();
}

and

<MudSelect T="multiselectitem" MultiSelection="true" SelectAll="true" ToStringFunc="@ToString" SelectedValues="@selectedtestitems" SelectedValuesChanged="SelectedValuesChanged">

https://try.mudblazor.com/snippet/cucxPEbgdzurqrtj