htmlselectdrop-down-menublazordefault-value

Set Default Value in HTML / Blazor Select (Dropdown) Foreach


I want to set a default Value from the foreach-loop in a Select List in HTML.

Thanks for your effort.

<select class="form-control" style="width: 160px" id="id">
@foreach (var option in Function())
{
    <option> @option </option>
}

Solution

  • If you want to be able to choose which value is selected and also get the updated value automatically, then you can use two-way binding:

    <select @bind="BindString">
        @foreach (var item in ValuesFromFunction)
        {
            <option>@item</option>
        }
    </select>
    <br/>
    <div>The selected value is: <b>@BindString</b></div>
    
    @code {
        string BindString { get; set; } = "Three";
        List<string> ValuesFromFunction = new() { "One", "Two", "Three" };
    }