I am trying to cancel the 'onchange' event for a element after capturing the selected value. Basically just to capture the selected value and return the select element selected item to where it was. How can i do this in Blazor?
<select @onchange="onSelectFilter">
<option value="0">Select a filter</option>
<option value="1">Filter 1</option>
<option value="2">Filter 2</option>
</select>
@code
{
private void onSelectFilter(ChangeEventArgs args)
{
var val = int.Parse(args.Value.ToString());
if (val != 0)
{
//do something
//reset the value to 0
args.Value = 0;
}
}
}
much simpler way to do it just in C#
@page "/"
<select @bind="Selected" class="form-control">
<option value="0">Select a filter</option>
<option value="1">Filter 1</option>
<option value="2">Filter 2</option>
</select>
<h1>@Captured</h1>
@code
{
int Captured;
int _Selected;
private int Selected
{
get{return _Selected;}
set{
Captured = value; //store the captured value
_Selected = 0; //reset the drop down
}
}
}
you can go even more minimal with this @code block
@code
{
int Captured;
int Selected
{
get{return 0;} // reset the select
set{Captured = value;} //store the captured value
}
}
InterOp
This solution works with a bit of JS and InterOp. After get new value, the code uses JS to change select
value to previous one.
Blazor code:
@inject IJSRuntime JsRuntime
<select id="mySelect" @onchange="onSelectFilter" class="form-control">
<option value="0">Select a filter</option>
<option value="1">Filter 1</option>
<option value="2">Filter 2</option>
</select>
<h1>@captured</h1>
@code
{
private string v;
private string captured;
private async void onSelectFilter(ChangeEventArgs args)
{
v = (string)args.Value;
captured = v;
v="0";
await JsRuntime.InvokeAsync<object>( //<--- Interop
"NewSelectValue",
"mySelect",
v);
}
}
The JS code (for example on _Host.cshtml
file ):
<script>
window.NewSelectValue = (id, newVal) => {
let e = document.getElementById(id);
e.value=newVal;
}
</script>
C#
You can do it forcing DOM changes from Blazor code, two steps. Notice I added value="@v"
to select
tag:
<select @onchange="onSelectFilter" value="@v" class="form-control">
<option value="0">Select a filter</option>
<option value="1">Filter 1</option>
<option value="2">Filter 2</option>
</select>
<h1>@captured</h1>
@code
{
private string v;
private string captured;
private async void onSelectFilter(ChangeEventArgs args)
{
// step 1:
v = (string)args.Value; // set new value
StateHasChanged();
await Task.Delay(1); // flush UI changes
// do tasks:
captured = v;
// step 2:
v="0"; // set default value
StateHasChanged();
await Task.Delay(1); // flush UI changes
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With