Home > Blockchain >  Blazor Server set multiple default values for select drop down list
Blazor Server set multiple default values for select drop down list

Time:05-15

I have a Blazor server app (.net 6) page that has a select drop down list, which is set to allow multiple selected items. I need to set default values, when the page loads. If I only want to set one selected value, this code works fine. But, if I want to set multiple values, it does not work. How can I set the select list default values, when there is more than one value I want to set? Here is what I have:

<select value ="@SelectedCities" @onchange="@((ev) => ListChangeEvent(ev, row_id ))"  aria-label="Default select example" multiple rows="4"> 
     @foreach (var i in item.values.ToList())
     {
       <option id="@i.Key">@i.Value</option> 
     }
</select>


public string[] SelectedCities { get; set; } = new[] { "New York", "Pittsburgh" };

The above code does not work. There are no errors, it simply does not select the two items.

But, if SelectedCities was not an array, like this:

public string SelectedCities { get; set; } = "New York";

It works fine.

thanks

CodePudding user response:


<select multiple @onchange=HandleChange>
    @foreach(var option in Options)
    {
        <option @key=@option selected=@(chosen.Contains(option)) value=@option>@option</option>
    }
</select>

<pre>@string.Join(", ",chosen)</pre>
@code
{
    string[] Options = new string[] {"Abc","Def","Ghi"};
    string[] chosen = new string[] {"Abc","Ghi"};
    void HandleChange(ChangeEventArgs args)
    => chosen = args.Value as string[];
}

Demo

  • Related