Search code examples
blazormudblazor

Mudblazor clear TextField after "Enter"


I am using Mudblazor component TextField in my Blazor Server project.

I want to clear the TextField after I press "Enter"

Here is my code in my Index.Razor :

@page :

<MudTextField class="pa-4" @bind-Value="newTodayTask" Clearable="true"
OnKeyUp="AddTodayTask" Adornment="Adornment.End" AdornmentIcon="@Icons.Outlined.Add"
FullWidth="false" Placeholder="Create a new task here, press Enter ↵ to save" Variant="Variant.Text" 
Style="width:600px; margin-bottom:10px"></MudTextField>

@code :

public string newTodayTask { get; set; }

protected async Task AddTodayTask(KeyboardEventArgs e)
{
    if(e.Key == "Enter")
    {
        if (!string.IsNullOrWhiteSpace(newTodayTask))
        {
            var result = false;                
            var todaytask = new TodayTaskModel { TaskName = newTodayTask, DueDate = dueDate, TaskCreatedBy = taskCreatedBy};
            result = await Service.CreateTodayTask(todaytask);
            StateHasChanged();
            newTodayTask = string.Empty;

        }

    }
    OnInitialized();  
}

I already try with string.Empty; and StateHasChanged(); but still not works.

I really appreciate any help that can provide. Thanks


Solution

  • On some platforms, hitting the "enter" key while a text control is focused implicitly submits the form, the implicit submission pattern.

    Because your form only has one input element, maybe, the most elegant solution is to use this pattern as UX for your data entry. You should to think on accessibility.

    I post a sample in try.mudblazor:

    enter image description here

    The source code:

    <MudPaper Class="pa-4">
        <EditForm Model="@model" OnValidSubmit="OnValidSubmit">
            <MudTextField 
                @bind-Value="@model.Name" 
                Immediate="true" 
                Label="Some Text and press enter" />
        </EditForm>
    </MudPaper>
    
    <ul>
    @foreach(var s in history)
    {
        <li>@s</li>
    }
    </ul>
    
    @code { 
        public class MyTask
        {
            public string Name {get; set;} = default!;
        }
        
        List<string> history = new List<string>();
    
        MyTask model =  new MyTask(){Name="hi"};
    
        private void OnValidSubmit()
        {
            history.Add(model.Name);
            model.Name = "";
            StateHasChanged();
        }
    
    }