Home > front end >  Blazor WASM - convert ChangeEventArgs to enum type
Blazor WASM - convert ChangeEventArgs to enum type

Time:11-17

I am writing an ASP.NET Blazor WASM program with an HTML select dropdown. It has a value attribute that is linked to an enum variable type, and calls a custom method with the @onchange directive.

Dropdown component

<select name="category" class="form-control selectpicker " value="@_searchCategory" @onchange="UpdateCategory">
    @foreach (var item in Enum.GetValues(typeof(SearchCategory)))
        {
            <option value="@item">@item</option>
        }
</select>

Search Variables

private SearchCategory _searchCategory = SearchCategory.Port;
private enum SearchCategory
    {
        Port,
        Name,
        Script,
        Version
    }

UpdateCategory method

UpdateCategory(ChangeEventArgs args) {
    _searchCategory = args.Value; //error
    PerformSearch();
...
}

What is the right way to update @_searchCategory without using @bind? I tried casting from String but no luck.

CodePudding user response:

Convert the args to string and then convert the string to SearchCategory as shown below.

private void UpdateCategory(ChangeEventArgs args) {
        var searchCategoryAsString = args.Value?.ToString();

        if (string.IsNullOrEmpty(searchCategoryAsString)) return;

        _searchCategory = (SearchCategory) Enum.Parse(typeof(SearchCategory), searchCategoryAsString);
        Console.WriteLine(_searchCategory);
    }
  • Related