onChange event not firing Blazor InputSelect

Note:

  • InputSelect is a component element, not HTML element, which is why you cannot
    apply to it the @onchange compiler directive. This directive is applied to
    elements, usually but not necessarily with the value attribute to form the so-
    called two way data-binding.

  • @bind-Value is a compiler directive directive instructing the compiler to
    produce code that enable two-way data binding between components. Applying
    @bind-Value to the InputSelect component requires you (already done in this
    case by the Blazor team) to define a parameter property named Value and an
    EventCallback ‘delegate’, conventionally named ValueChanged. Value and
    ValueChanged are properties of the InputSelect component.

There are a couple of ways to do this:

 <InputSelect ValueExpression="@(()=>comment.Country)" 
              Value="@comment.Country" 
              ValueChanged="@((string value) => OnValueChanged(value ))">
        <option value="">Select country...</option>
        <option value="USA">USA</option>
        <option value="Britain">Britain</option>
        <option value="Germany">Germany</option>
        <option value="Israel">Israel</option>
 </InputSelect>

And

private Task OnValueChanged(string value)
{
    // Assign the selected value to the Model 
    comment.Country = value;
    return Task.CompletedTask;
} 

You can also implement INotifyPropertyChanged.PropertyChanged Event in your Model, as dani herrera has suggested. You do that if you want to do away with the Forms components, including the EditForm, and use the normal HTML tags instead, in which case you’ll be able to do something like:

<input type="text" value="@MyValue" @onchange=OnChange"/>

Of course your model class is going to be thick, and it should communicate with the EditContext….

Hope this helps…

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)