I'm building a barcode scanner page using Blazor and MudBlazor. When I click the "Add" button, the barcode is successfully submitted, and the input field is cleared. However, when I press the Enter key to submit, the product is added, but the input field does not clear even though I'm resetting the Barcode variable.
Here is the relevant part of my code:
<MudTextField Label="Enter Barcode" @bind-Value="Barcode" Variant="Variant.Filled" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.QrCode" Immediate="true" Class="barcode-text" OnKeyDown="HandleKeyPress"/>private async Task HandleKeyPress(KeyboardEventArgs e){ if (e.Key == "Enter") { await SubmitBarcode(); Barcode = ""; // trying to clear the field }} private async Task SubmitBarcode() { if (string.IsNullOrWhiteSpace(Barcode)) { Message = "Please enter a barcode."; await JS.InvokeVoidAsync("focusElement"); return; } var response = await Http.PostAsync( $"http://localhost:5191/Product/Add?BarCode={Uri.EscapeDataString(Barcode)}", null ); if (response.IsSuccessStatusCode) { var product = new Product { Barcode = Barcode, Name = $"Product {Products.Count + 1}" }; Products.Add(product); Message = "Barcode added successfully!"; Barcode = ""; } else { Message = "Failed to add barcode."; } await JS.InvokeVoidAsync("focusElement"); }The SubmitBarcode method works correctly — it adds the product and sets Barcode = "". This works fine with the button click, but not with the Enter key.
What am I missing? Why doesn't the input field get cleared when submitting with Enter?