blazor dropdown onchange code example
Example 1: blazorstrap dropdown onchange
//Your answer should be in the cshtml:
<select class="form-control" @onchange="@OnSelect" style="width:150px">
@foreach (var template in templates)
{
<option value=@template>@template</option>
}
</select>
<h5>Selected Country is: @selectedString</h5>
//Then your @functions or @code if Blazor should look like:
@code {
List<string> templates = new List<string>() { "America", "China", "India", "Russia", "England" };
string selectedString = "America";
void OnSelect (ChangeEventArgs e)
{
selectedString = e.Value.ToString();
Console.WriteLine("The selected country is : " + selectedString);
}
}
Example 2: blazor component ValueChanged
<h1>Child Component</h1>
Password:
<input @oninput="OnPasswordChanged"
required
type="@(showPassword ? "text" : "password")"
value="@Password" />
<button class="btn btn-primary" @onclick="ToggleShowPassword">
Show password
</button>
<span class="text-danger">@validationMessage</span>
@code {
private bool showPassword;
private string password;
private string validationMessage;
[Parameter]
public string Password
{
get { return password ?? string.Empty; }
set
{
if (password != value)
{
if (value.Contains(' '))
{
validationMessage = "Spaces not allowed!";
}
else
{
password = value;
validationMessage = string.Empty;
}
}
}
}
[Parameter]
public EventCallback<string> PasswordChanged { get; set; }
private Task OnPasswordChanged(ChangeEventArgs e)
{
Password = e.Value.ToString();
return PasswordChanged.InvokeAsync(Password);
}
private void ToggleShowPassword()
{
showPassword = !showPassword;
}
}