0

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

2 Answers 2

1

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" };
}
Sign up to request clarification or add additional context in comments.

Comments

1

Use

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

3 Comments

I dont want to get a new value, but i want to get a specific value from the foreach list.
you have to use this line only for an option which you want to select by default. Just put on @if(condition){ my line } else{ your line }.
You can definitely use a condition in your foreach as Jay suggested, but I think maybe you are looking for 2-way binding? Let me know if my answer is what you meant.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.