How to implement <select multiple> in blazor server?
According to the tutorial, I create a net7.0 Blazor server application, then add the JavaScript script in the _Host.cshtml page (if your application is an Asp.net 6 application, you should add the script in the _Layout.cshtml page),
<script>
window.getSelectedValues = function (sel) {
var results = [];
var i;
for (i = 0; i < sel.options.length; i++) {
if (sel.options[i].selected) {
results[results.length] = sel.options[i].value;
}
}
return results;
};
</script>
Then, create a MultipleSelect component with the following code:
@page "/mulselect"
@inject IJSRuntime JS;
<h3>MultipleSelect</h3>
<select @ref="_selectReference" @onchange="OnSelectionChanged" multiple>
@foreach (var option in AllOptions)
{
<option value="@option" selected="@Model.SelectedOptions.Contains(option)">@option</option>
}
</select>
<div>
<table>
<tr>Task</tr>
@foreach (var item in Model.SelectedOptions)
{
<tr>@item</tr>
}
</table>
</div>
@code {
private List<string> AllOptions;
//based on the select element to create a model.
private TestModel Model;
private class TestModel
{
public HashSet<string> SelectedOptions { get; set; }
}
//set the initial data
protected override async Task OnInitializedAsync()
{
AllOptions = new List<string>() { "Items A", "Item B", "Item C", "Item D", "Item E" };
Model = new TestModel() { SelectedOptions = new HashSet<string>() { "Item B", "Item D" } };
}
private ElementReference _selectReference;
//select change event.
private async Task OnSelectionChanged(ChangeEventArgs eventArgs)
{
var selection = await GetSelections(_selectReference);
Model.SelectedOptions = selection;
}
public async Task<HashSet<string>> GetSelections(ElementReference elementReference)
{
return (await JS.InvokeAsync<List<string>>("getSelectedValues", _selectReference)).ToHashSet();
}
}
After that, running the application, the result as below:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion