DropDown fires OnChange twice

Environment

Product DropDownList for Blazor, ComboBox for Blazor, AutoComplete for Blazor, TextBox for Blazor, NumericTextBox for Blazor

Description

I observe twice firing onchange event in dropdownlist.

I want the event to fire only once when the user selects something.

Cause\Possible Cause(s)

The OnChange event is a user confirmation event - it fires when the user chooses an item from the dropdown list, and also when the user blurs an input (the dropdownlist is, in essence, an input).

Solution

If you want to execute some business logic (such as fetching data) only once per value change, but you want to keep using the @bind-Value to populate your models, you can keep the last value with which OnChange fired and compare against it.

Execute OnChange once per value selection

@* monitor the console and try the following to see the difference:
    - selecting the same item several times
    - clicking away from the dropdownlist after selecting an item
    *@

@MySelectedItem
<br />
<TelerikDropDownList Data="@MyList" OnChange="@MyOnChangeHandler" @bind-Value="@MySelectedItem">
</TelerikDropDownList>

@code {
    string MySelectedItem { get; set; }
    protected List<string> MyList = new List<string>() { "first", "second", "third" };

    string lastOnChangeValue { get; set; }

    void MyOnChangeHandler(object theUserInput)
    {
        string currValue = theUserInput as string;

        Console.WriteLine($"OnChange fired for value: {currValue}");

        if (!currValue.Equals(lastOnChangeValue))
        {
            //this is where you execute the business logic you want to fire once per selected value
            Console.WriteLine($"Executing business logic for value {currValue}, such as loading data");
        }

        lastOnChangeValue = currValue;
    }
}
In this article
Not finding the help you need? Improve this article