maxba
maxba

Reputation: 27

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>
}

Upvotes: 0

Views: 2085

Answers (2)

Bennyboy1973
Bennyboy1973

Reputation: 4208

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" };
}

Upvotes: 1

Jai248
Jai248

Reputation: 1649

Use

<option value="value" selected>Option Name</option>

Upvotes: 1

Related Questions