1

I've created a Blazor server app targeting .NET 6.0.

I then add a combo-box to the default Counter.razor page like this

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

<p>
    <label>
        Select a car:
        <select @onchange="SelectedCarsChanged" >
            <option value="">Select a car</option>
            <option value="audi">Audi</option>
            <option value="jeep">Jeep</option>
            <option value="opel">Opel</option>
            <option value="saab">Saab</option>
            <option value="volvo">Volvo</option>
        </select>
    </label>
</p>

Here's the @code section after the combo-box addition.

    private int currentCount = 0;
    private void IncrementCount()
    {
        currentCount++;
    }
    string SelectedCar = "";
    void SelectedCarsChanged(ChangeEventArgs e)
    {
        if (e.Value is not null)
        {
            SelectedCar = (string)e.Value;
        }
    }

The user selects a car and then presses the "Click me" button.

How do I reset the combo-box to "Select a car" in the IncrementCount() routine when that happens?

AlexVPerl
  • 7,652
  • 8
  • 51
  • 83
Hal Heinrich
  • 544
  • 1
  • 4
  • 21
  • Does this answer your question? [Blazor select dropdown set active value by code](https://stackoverflow.com/questions/60599131/blazor-select-dropdown-set-active-value-by-code) – Yong Shun Mar 03 '22 at 03:01

1 Answers1

1

You are almost there, bind SelectedCar to select like this

 <select @bind=@SelectedCar>
            <option value="">Select a car</option>
            <option value="audi">Audi</option>
            <option value="jeep">Jeep</option>
            <option value="opel">Opel</option>
            <option value="saab">Saab</option>
            <option value="volvo">Volvo</option>
        </select>

And select SelectedCar like this

 private void IncrementCount()
    {
        currentCount++;
        SelectedCar = "";
    }
Surinder Singh
  • 1,165
  • 1
  • 3
  • 11