Blazor: How to use the onchange event in <select> when using @bind also?

Mike picture Mike · Sep 27, 2019 · Viewed 13.4k times · Source

I need to be able to run a function after a selection in made in a <select>. The issue is I'm also binding with @bind and I get a error when I try to use @onchange stating that it is already in use by the @bind. I tried using @onselectionchange, but that does nothing(doesn't run the function). I could forget the @bind and just assign @onchange to a function, but I'm not sure how to pass the selected value to the function.

I have the following code:

<select @bind="@SelectedCustID" @ @onchange="@CustChanged" class="form-control">
    @foreach (KeyGuidPair i in CustList)
    {
        <option value="@i.Value">@i.Text</option>
    }
</select>

Thanks.

Answer

Zsolt Bendes picture Zsolt Bendes · Sep 27, 2019
<input @bind="MyProperty" />

@code  {
    private string myVar;

    public string MyProperty
    {
        get { return myVar; }
        set
        {
            myVar = value;
            SomeMethod();
        }
    }

    private void SomeMethod()
    {
        //Do something
    }
}