jeudi 16 février 2023

How to list checked enum values only?

I’m learning Blazor and was trying to put/save in a list some enum elements, only the ones that are checked. I have read loads of hints on stackoverflow and other web sites but am still unable to achieve that, I know something is missing but I’m blind for now

Let’s say I have an enum in a separate class calle Enums:

    public enum Browsers
    {
        Chrome,
        Edge,
        Firefox,
        Opera,
        Safari,
        Vivaldi
    }

Here is the html part:

@page "/Sub2"
@using TestPatternBuilder.Data

<div class="col">
    <div>Browsers:</div>
        @foreach (var browser in Enum.GetValues<Browsers>())
        {
            <input class="form-check-input mx-0" type="checkbox" id="browsers" value="@browser" />
            <label class="ms-1" for="browsers">@browser</label><br />
        }

    <button class="btn btn-secondary my-3" @onclick="AddBrowsers">Add Browsers</button>

    <ul class="mt-2">
        @foreach (var br in selectedBrowsers)
        {
            <li>@br.BrowserName</li>
        }
    </ul>
</div>

And the code part:

@code{

    List<TestBrowser> selectedBrowsers = new List<TestBrowser>();

    private void AddBrowsers()
    {
        foreach (Browsers item in Enum.GetValues(typeof(Browsers)))
        {
            selectedBrowsers.Add(new TestBrowser { BrowserName = item, isChecked = true });
        }
    }

}

I seem to have it all wrong, tried to bind without success, no idea where the isChecked state is missing...

[enter image description here](https://i.stack.imgur.com/R7y6a.png)




Aucun commentaire:

Enregistrer un commentaire