So I would think this would be a simply thing to do but I can't seem to make it work for the life of me. Essentially all I'm trying to do is take the template client side Blazor project and add a POST to the button click that updates some UI based on what is returned from that.

The POST does go out and does get a response (as verified by the browser) but the UI never gets updated. In fact as far as I can tell the method gets blocked indefinitely.


<button class="btn btn-primary" onclick="@IncrementCount">Click me</button>

@functions {
    string callResult = string.Empty;

    async void IncrementCount()
        // Create something to send
        Dictionary<string, string> values = new Dictionary<string, string>();
        values.Add("hello", "world");

        // Encode it
        var content = new FormUrlEncodedContent(values);

        // Send it
        var response = await httpClient.PostAsync(" url...", content);

        // Read response
        callResult = await response.Content.ReadAsStringAsync();        

I understand that being an async call the function returns before it has a chance to update the UI but I've even tried calling this.StateHasChanged() or even setting ConfigureAwait(false) and still nothing.

I'm sure there's something wrong with my pattern here but I'm just not seeing it. Any help would be appreciated.

1 Answers

Issac On

Provided your HttpClient has been properly configured (Actually all you've got to do is to inject the HttpClient service into your component, thus: @inject HttpClient httpClient), you can do the following:

  • Base your call on the following method signature:

    public static Task PostJsonAsync(this HttpClient httpClient, string requestUri, object content)

Note: T is the type into which the response body is JSON-deserialized by Blazor

Note that your content is internally serialized by Blazor before it is posted( Json.Serialize)

I hope this helps