How to use html dropdown in Blazor



While working on a Blazor project, so many times we will use plain HTML dropdown. In this scenario, we will get a requirement to trigger the event and reset the selection item to the initial state.

Here are some code snippets for completing this task.

Approach 1:

@page "/counter"

<select @onchange="OptionChanged" value="@selectedOption">
    <option value="-1">Select Option</option>
    @foreach (var option in options)
    {
        <option value="@option">@option</option>
    }
</select>

<button @onclick="ClearSelection">Clear Selection</button>

@code {
    private List<string> options = new List<string> { "Option 1", "Option 2", "Option 3" };
    private string selectedOption { get; set; } = "-1"; // Set default value to "-1"

    private void OptionChanged(ChangeEventArgs e)
    {
        // Extract the selected value from the event argument
        string selectedValue = e.Value.ToString();
        Console.WriteLine($"Selected option: {selectedValue}");
        // Assign the selected value to the selectedOption variable
        selectedOption = selectedValue;
    }

    private void ClearSelection()
    {
        // Clear the selected option
        selectedOption = "-1"; // Reset to default value "-1"
        StateHasChanged(); // Trigger a UI update
    }
}

Approach 2:

@page "/"

<PageTitle>Home</PageTitle>

<select @onchange="OptionChanged" value="@selectedOption">
    <option value="">Select Option</option>
    @foreach (var option in options)
    {
        <option value="@option">@option</option>
    }
</select>

<button @onclick="ClearSelection">Clear Selection</button>

@code {
    private List<string> options = new List<string> { "Option 1", "Option 2", "Option 3" };
    private string selectedOption { get; set; } = "";

    private void OptionChanged(ChangeEventArgs e)
    {
        // Extract the selected value from the event argument
        string selectedValue = e.Value.ToString();
        Console.WriteLine($"Selected option: {selectedValue}");
        // Assign the selected value to the selectedOption variable
        selectedOption = selectedValue;
    }

    private void ClearSelection()
    {
        // Clear the selected option
        selectedOption = "";
        // Trigger a UI update
        StateHasChanged();
    }
}

Summary:

In this code snippet, we demonstrate how to handle various scenarios using an HTML dropdown in Blazor.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.