I have a Blazor app.
If I add a select element like so:
<select multiple name="cars" id="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
all is well. It displays a simple list box and I can multiple select.
Now I add this variable:
private string[] m_otherClients = {"Volvo", "Saab", "Open", "Audi"};
And I alter the declaration of the select like so:
<select multiple @bind="m_otherClients" name="cars" id="cars">
@if (m_otherClients != null)
{
@foreach (var cnt in m_otherClients)
{
<option value="@cnt">@cnt</option>
}
}
</select>
Now the listbox displays but with all items highlighted and when I click on one of them m_otherClients changes it’s value and now contains only the item I clicked on, and so the UI updates and now the listbox has only this item in it.
How can I prevent the clicking on the select from altering the value of m_otherClients?
>Solution :
In your code, when you use @bind="m_otherClients" with the <select> element, you’re binding the selected values directly to the m_otherClients array. This is why when you click an option in the select box, it changes the value of m_otherClients to just the clicked option.
If you want to prevent the m_otherClients array from changing when an option is clicked, you should not use @bind for this specific <select> element. Instead, you can handle the selection manually using JavaScript and update the selected items without affecting the underlying data source. Here’s an example of how you can do this:
<select multiple name="cars" id="cars">
@foreach (var cnt in m_otherClients)
{
<option value="@cnt" selected="@m_otherClients.Contains(cnt)" @onchange="ToggleSelection">@cnt</option>
}
</select>
@code {
private string[] m_otherClients = { "Volvo", "Saab", "Open", "Audi" };
private void ToggleSelection(ChangeEventArgs e)
{
var selectedValue = e.Value.ToString();
if (m_otherClients.Contains(selectedValue))
{
m_otherClients = m_otherClients.Where(item => item != selectedValue).ToArray();
}
else
{
m_otherClients = m_otherClients.Concat(new[] { selectedValue }).ToArray();
}
}
}
In this code, we are manually handling the selection and deselection of options in the <select> element. The ToggleSelection method is called when an option is changed (clicked), and it updates the m_otherClients array accordingly. This way, the array won’t change unless you explicitly modify it, and the UI will reflect the selected items as you toggle them.