skip to Main Content

The MudTextField is bound to variable chatInput. Once user inputs their query and hits Enter, HandleKeyUp() is called. In that method, we grab the value of the query and then clear the field and attempt to update the state. The variable bound to the field changes to an empty value in debug, however the UI does not clear the text. We want the text clear, so the user can more easily type another query there.

Tech Stack: Blazor Server, MudBlazor, C#.

// Clear the input
   chatInput = string.Empty;
  
// Trigger UI update to clear the input field
   await InvokeAsync(StateHasChanged);

//Part of the MudBlazor element
 MudTextField @bind-Value="chatInput" Placeholder="Type a message"
 @bind-Value:after="@(() => InvokeAsync(StateHasChanged))"  
 @onkeyup="HandleKeyUp"

2

Answers


  1. Here’s a possible workaround, without javascript. According to the link at the bottom, in server-side rendering, the textfield updates when the input looses focus.

    <MudTextField @ref="messageField" @bind-Value="@chatInput" Placeholder="Type a message" OnKeyUp="HandleKeyUp"/>
    
    @code {
        private string chatInput = string.Empty;
        private MudTextField<string> messageField = default!;
    
        private async Task HandleKeyUp(KeyboardEventArgs e)
        {
            if (e.Key == "Enter")
            {
                var result = await SendChatMessage(chatInput);
                if (result)
                {
                    await messageField.BlurAsync();
                    chatInput = "";
                    // Should not be needed to call StateHasChanged from my testing
                    // StateHasChanged();
                    await messageField.FocusAsync();
                }
            }
        }
    
        private ValueTask<bool> SendChatMessage(string message)
        {
            // Send message to server
            return ValueTask.FromResult(true);
        }
    }
    

    Was struggling myself, but found the workaround here:
    https://stackoverflow.com/a/77290588/3616319

    Login or Signup to reply.
  2. You could use "@ref"."clear()" to clear the bind value.

    @page "/"
    @rendermode InteractiveServer
    
    <MudTextField @ref="txt1" @bind-Value="chatInput" OnKeyUp="HandleKeyUp"></MudTextField>
    
    @code{
        private MudTextField<string> txt1;
        private string chatInput;
    
        private void HandleKeyUp(KeyboardEventArgs args){       
            if (args.Key == "Enter")
            {
                Console.WriteLine(chatInput);
                txt1.Clear();
            }
        }
     }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search