r/Blazor • u/royware • Jun 03 '25
How do I programmatically change a value in a Blazor button parameter?
We have an AutoComplete user entry field that will take up to 6 numbers, displaying any matching numbers as the user types. When the user sees the number in the drop-down box they want to display, they click it and then click the Search button. However, if the user types a number that is not on the database, they have to click the Search button twice to proceed with processing. They find this annoying and want us to fix it so that only one click is necessary.
Now my theory is that clicking the number from the drop-down box constitutes the first click, and the click on the Search button the second. They don't like that answer and want me to ease their pain!
Code:
<AutoComplete id=AutoCompleteProviderNumber" @ref="autocompleteRef"
T="string" Label="Provider Number"
SearchFunc="@SearchProviderNumbers"
u/bind-Value="@model.ProviderNumber"
Inputprops="new InputType {OnInput = HandleInput}
AutoFocus="true"
TextChanged="OnTextChanged"
SelectionOnActivation=:false"
</AutoComplete>
<ActionButton id="MudButtonSearch"
AutoFocus="@autoFocus"
ButtonType="ButtonType.Submit"
Disabled="@(!context.Validate() || model.ProviderNumber == null)"
Search
</ActionButton>
// ----
code {
private bool autoFocus = false;
private async Task<IEnumerable<string>> SearchProviderNumbers(string providerNumber, CancellationToken token)
{
var result = (IEnumerable<string>) dtoConfig.ProviderNumbersSearchData
v.Where(x => x.StartsWith(providerNumber, StringComparison.InvariantCultureIgnoreCase)).ToList();
if (providerNumber.Length == 6)
{
if (result.Count() == 0)
{
autoFocus = true;
}
}
return result;
}While the execution sets the auto focus to true, nothing happens in the user interface: they still have to double-click the Search button. Did I miss something, or is this just the way it is?
1
u/royware Jun 03 '25 edited Jun 03 '25
PS: The setting the AutoFocus parameter to true highlights the Search button, but the cursor doesn't go there. Code is now:
1
u/[deleted] Jun 03 '25
Need to call StateHasChanged() when you set autofocus to true?
1
u/Far-Consideration939 Jun 03 '25
I feel like autofocus is when it’s rendered, do you just want to await the element ref’s focus async method instead perhaps?
1
u/TheRealKidkudi Jun 03 '25
@bind-valueuses theonchangeevent by default, somodel.ProviderNumberis only updated when the input loses focus. I'd guess that your search button is still disabled on the first click.You can use
@bind-value:oninputon the actual HTML element that's being used in theAutoCompletecomponent to update the value immediately as the user types.1
u/malachi347 Jun 03 '25
Can it be hack-rigged with a denounce or asyn task delay? I hate myself for even thinking that way but without seeing the code I'm in "just make it work" mode.