Blazor: Select all option in dropdown

731 Views Asked by At

So I pretty much have a dropdown (for filterting purposes) currently where you can select a fruit from a list which is pretty much a list which contains FruitDtos, and it works perfectly fine. However, I would like to add an "All" option, but I'm unsure how to do that.

It looks like this in the .razor file:

                <Addon AddonType="AddonType.Body">
                    <Select TValue="int" SelectedValue="@SelectedListValue" SelectedValueChanged="@OnFruitChanged">
                        @foreach (FruitDto item in _fruitsList)
                        {
                            <SelectItem Disabled="@(item.FruitId == 0)" Value="@item.FruitId">@item.Name</SelectItem>
                        }
                    </Select>
                </Addon>

So _fruitsList contains all of the FruitDtos. Is there a way I can let the user select all of them at once? Tbh, I mostly want this option because right now you need to refresh the page in order to "deselect"/remove the filter.

int SelectedListValue { get; set; }
[Parameter] public FruitDto Fruit { get; set; }
        private async Task OnFruitChanged(int newValue)
        {
            SelectedListValue = newValue;

            Fruit = _fruitsList.Find(s => s.FruitId == newValue);
            await FruitChanged.InvokeAsync(Fruit);
            StateHasChanged();
        }

FruitDto just contains a string Name and int FruitId.

1

There are 1 best solutions below

0
Wildxmo On

Blazorise's Select component offers a "Multiple" option as well. That might work well for what you are asking. Note that I did remove the Disabled attribute as I'm not sure how that was being used.

.razor:

<Select TValue="int" Multiple="true" SelectedValuesChanged="@OnFruitChanged">
    @foreach (FruitDto item in _fruitsList)
    {
        <SelectItem Value="@item.FruitId">@item.Name</SelectItem>
    }
</Select>

.cs:

protected List<int> SelectedListValues { get; set; }

protected void OnFruitChanged(IReadOnlyList<int> newValues)
{
    SelectedListValues = newValues.ToList();
}

If you want to clear the list, you could add a button "Clear Filters" which would have on OnClick to clear the list as well.