Search code examples
blazorblazor-hybrid

InputSelect with enum binding, how launching additionnal tasks?


I have an enum and a variable of the enum type as follows:

private enum Cities {Berlin, Madrid, Paris, Vienna}
private Cities City;

In the html I have a InputSelect component as follows:

<InputSelect @bind-Value="City">
@foreach(var city in Enum.GetValues(typeof(Cities)))
{
    <option value="@city">@city</option>
}
<br />
@City

This is working fine, and each time I select another city the variable city is updated.

enter image description here

The issue I have is that I need to execute some tasks when a new city is selected. So I need to attach a function to the InputSelect. I cannot add ValueChanged because of the binding. I tried also the following:

<InputSelect ValueChanged="(e)=>TestFunction(e)">
@foreach(var city in Enum.GetValues(typeof(Cities)))
{
    <option value="@city">@city</option>
}
</InputSelect>

But it gives an error. enter image description here

I don't know what to do to make it work. Maybe someone has an idea.


Solution

  • You don't need to use the Blazor input components unless you are using the built-in validation that comes with EditForm. I use vanilla HTML 99% of the time.

    If you want to handle any kind of html input change yourself (not just select), you can provide an onchange method, and handle the arguments yourself. You can see the expected signature by hovering over @onchange after you type it.

    <select @onchange=HandleCitySelection>
        <option selected disabled>Select a city. . . </option>
        @foreach (var city in Enum.GetValues(typeof(Cities)))
        {
            <option value="@city">@city</option>
        }
    </select>
    @if(City is not null)
    {
        <div>You selected "@City."</div>
    }
    
    @code {
        private enum Cities { Berlin, Madrid, Paris, Vienna }
        private Cities? City;
    
        async Task HandleCitySelection(ChangeEventArgs e)
        {
            City = (Cities)Enum.Parse(typeof(Cities), e.Value.ToString());
            // Do stuff
        }
    }