Search code examples
async-awaithttp-postblazorblazor-webassembly

Http client in Blazor webassembly on success post as it was in jQuery


I am switching from asp.net mvc to blazor webassembly.
In mvc when I need to post something to controller I am using jQuery ajax post e.g.

$.ajax({
        method: "post",
        type: "post",
        contentType: "application/json; charset=utf-8",
        url: "../../Tabele/Clone",
        traditional: true,
        data: data,
        success: function (data, status, xhr) {
                logujError (data.msg)  
        },
        error: function (xhr) {
            console.log("puko si kod postajExtraDetalje", xhr.responseText); //,xhr.statusText, 
        }
    });

Now when in blazor I need to post data I am using HttpClient e.g.

    var response = await Http.PostAsJsonAsync<ConfigView>($"/api/Vage/Cofnig", configView);
    if (response.IsSuccessStatusCode)
    {
       var data= await response.Content.ReadFromJsonAsync<PocoMsgId>();
       logujError (data.msg)  
    }
else {
// handel error
}

Do I understand C# and async methods correctly my gui is frozen until post is over because I am awaiting two times? How I can do post data and display results in gui using Http client in blazor webassembly without to freeze guid during posting data and waiting for results?


Solution

  • If you are using asynchrony, there shouldn't be any issue. It is true that JS and WebAssembly are single-threaded, but this has nothing to do with the ability to use
    asynchrony. When you run your code and use the await key word, execution of your code is yielded to the calling code that continues to do things such as re-rendering the UI. When your async method, say PostAsJsonAsync returns, execution of the current method continues...

    When the second method, response.Content.ReadFromJsonAsync, is called, once again, execution is yielded to the calling code that continues to do things such as re-rendering the UI, and so on and so forth.

    Does this mean that regarding gui there is no difference between ajax onsuccess event call back and awaiting to get results in Httpclient on WebAssembly?

    In a sense yes... As a matter of fact the HttpClient service's methods such as PostAsJsonAsync, GetAsJsonAsync are ajax calls, as those methods are implementing the JavaScript Fetch Api (in Blazor webassembly, right ? ).

    But this is C# + .Net, not JavaScript. Your focus should be on the employment of asynchrony in .Net, how to use it and why. I'll demonstrate it in using the code from the default template's FetchData page:

    @page "/fetchdata"
    @inject HttpClient Http
    
    <h1>Weather forecast</h1>
    
    <p>This component demonstrates fetching data from the server.</p>
    
    @if (forecasts == null)
    {
        <p><em>Loading...</em></p>
    }
    else
    {
        <table class="table">
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Temp. (C)</th>
                    <th>Temp. (F)</th>
                    <th>Summary</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var forecast in forecasts)
                {
                    <tr>
                        <td>@forecast.Date.ToShortDateString()</td>
                        <td>@forecast.TemperatureC</td>
                        <td>@forecast.TemperatureF</td>
                        <td>@forecast.Summary</td>
                    </tr>
                }
            </tbody>
        </table>
    }
    
    @code {
        private WeatherForecast[] forecasts;
    
        // This method runs asynchronously. It is executed on the 
        // creation of a component.
        protected override async Task OnInitializedAsync()
        {
            // When code execution reaches this line, the await 
            // instruction calls the GetFromJsonAsync method, and  
            // then yield execution to the calling code. While awaiting 
            // for the method to return, Blazor starts rendering the 
            // component, which is why you must ensure that the variable
            // forecasts is not null (`@if (forecasts == null)`). At this 
            // time the variable forecasts is null, so no rendering 
            //occurs here...
            // When GetFromJsonAsync returns, the variable forecasts
            // is assigned the returned value (WeatherForecast[]),
            // and a second attempt is made to re-render the component,
            // this time successfully.
            forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>
        }
    }
    

    But asynchrony is enabled and required here, when performing ajax calls. Asynchrony is essential, especially when you make long-running calls

    You may generalize about callbacks, promises, and async/await in JavaScript being something similar to Task and async await in C#