Search code examples
c#blazor-webassembly.net-7.0mudblazor

Is there a possibility to get the Index of a selecte Item in a Mudlist?


I have a list of objects i print in a mudlist and i want to get the object behind the currently selected MudListItem.

I tried this already:

<MudList Clickable="true" @bind-SelectedItem="selectedItem" @bind-SelectedValue="selectedValue">

 @foreach (Branch branch in branches)
{
  <MudListItem Text="@branch.BranchName"></MudListItem>
}

</MudList>
@code {
    private List<Staff?> staffs = new List<Staff>();

    private List<Branch> branches = new List<Branch>();

    MudListItem selectedItem { get; set; }

        Staff staff = new Staff
            {
                FirstName = FirstName,
                LastName = LastName,
                Adr = adress,
                Br = branches[GetIndexOf(selectedItem)]
            };

}


Solution

  • You can assign an index with the value attribute on MudListItem. Mudblazor Documentation - Lists/Selection

    <MudListItem Text="@branch.BranchName" value="IndexOfbranch"></MudListItem>
    

    The value of value (IndexOfbranch) will then be assigned to selectedValue

    So you can then use it as

        Staff staff = new Staff
            {
                FirstName = FirstName,
                LastName = LastName,
                Adr = adress,
                Br = branches[selectedValue]
            };
    

    Mudblazor snippet, assign index