Home > OS >  How do I await an async Task from the oninput event of a textbox in Blazor?
How do I await an async Task from the oninput event of a textbox in Blazor?

Time:05-09

My Blazor component looks like this:

<input type="text" @bind-value="@MyText" @bind-value:event="oninput" />

@code {
    private String myText;
    protected String MyText
    {
        get { return myText; }
        set
        {
            myText = value;
            //await GetMyHttp();
        }
    }
    private async Task GetMyHttp()
    {
        HttpClient Http = _httpClientFactory.CreateClient("MyId");
        myData = await Http.GetFromJsonAsync<MyData>("MyParams");
    }
}

And this works fine. But if I uncomment the await GetMyHttp(); line,
I get this compilation error:
Error CS4033 The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.

How do I refactor this code to await the async method when the user types in the text box?

CodePudding user response:

It should be something like this:

<input type="text" value="@myText" @oninput="GetMyHttp" />

@code {
    private string myText;
   
    private async Task GetMyHttp(ChangeEventArgs args)
    {
        // This completes the two way data binding...
        myText = args.Value.ToString();

        // Are you going to perform an Http call at each stroke
        HttpClient Http = _httpClientFactory.CreateClient("MyId");
       
        // Where is myData defined ?
        myData = await Http.GetFromJsonAsync<MyData>("MyParams");
    }
}

Note: You can call the GetMyHttp method from the MyText property without issue, but I won't recommand you to code like this, unless there is not other way around to do that...

Fire and forget...

set
{
    myText = value;
    _ = GetMyHttp();
}

CodePudding user response:

You can have your MyText property getter and setter like this

protected String MyText
{
    get => myText;
    set
    {
        myText = value;
        Task.Run(()=> GetMyHttp());
    }
}
  • Related