Note: The onselect event fires after some text has been selected in an element. It has nothing to do with the select element or selection of options...
As far as I remember, the InputSelect had some issues, but these may have already been dealt with by the Blazor team.
The following code snippet describes how you can use the select element in Blazor, and how to implement a two-way data binding; that is, from a variable to an element, and from an element to a variable. You can do that in various ways: my code employs the most efficient way to achieve this goal, according to maestro Steve Anderson.
Here's the code snippet that bind the SelectedAuthorID variable to the select element employing two-way data binding.
<select @bind="@SelectedAuthorID">
<option value=@(0)></option>
@foreach (var author in authors)
{
<option value="@author.ID">@author.Name</option>
}
</select>
Note: The SelectedAuthorID is a property which defines a backing private variable:
int _selectedAuthorID;
private int SelectedAuthorID
{
get => _selectedAuthorID;
set
{
if (_selectedAuthorID != value)
{
_selectedAuthorID = value;
}
}
}
Well, this code is quite self-explanatory, but if you're not completely understand what I did, don't hesitate to ask.
The authors object in the foreach loop above is a list of authors you can create as follows:
@code {
List<Author> authors= Enumerable.Range(1, 10).Select(i => new Author { ID
= i, Name = $"Author {i.ToString()}" }).ToList();
public class Author
{
public int ID { get; set; }
public string Name { get; set; }
}
}
Now, let's try to model my options after the value="@availableLayouts.GetValue(1)" expression . This expression is evaluated to a string literal, right ? And when the user select this option, the OnSelectStock is called to do something.
Let's say that we want to call an OnSelectStock method and pass it the author id when an author is selected, and his id is even. Thus we can do something like this:
if (_selectedAuthorID != value)
{
_selectedAuthorID = value;
if(value % 2 == 0)
{
OnSelectStock( value );
}
}
This is it.
Hope this helps...
Complete working code:
Index.razor
@page "/"
<select @bind="@SelectedAuthorID">
<option value=@(0)></option>
@foreach (var author in authors)
{
<option value="@author.ID">@author.Name</option>
}
</select>
<p>Selected Author ID: @authorID</p>
@code{
string authorID;
int _selectedAuthorID;
private int SelectedAuthorID
{
get => _selectedAuthorID;
set
{
if (_selectedAuthorID != value)
{
_selectedAuthorID = value;
// Call OnSelectStock only if the author ID is an even number
if (value % 2 == 0)
{
OnSelectStock(value);
}
}
}
}
List<Author> authors = Enumerable.Range(1, 10).Select(i => new Author
{ ID = i, Name = $"Author {i.ToString()}" }).ToList();
private void OnSelectStock(int value)
{
authorID = value.ToString();
}
public class Author
{
public int ID { get; set; }
public string Name { get; set; }
}
}