1

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();
...
}

How can I cast string (args.Value) to Enum (SearchCategory)?

Ergis
  • 1,105
  • 1
  • 7
  • 18
Nate
  • 53
  • 3
  • What was your problem again? You are trying to cast a string (args.Value) to an Enum...so... – Ergis Nov 16 '21 at 20:00
  • @Ergis yeah that's the problem I am having now. I already tried casting with (SearchCategory) – Nate Nov 16 '21 at 20:10

1 Answers1

3

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);
    }
The Backer
  • 568
  • 1
  • 3
  • 10