我正在从asp.net mvc切换到blazor webassembly
在mvc中,当我需要向控制器发布内容时,我使用jQuery ajax帖子,例如
$.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,
}
});
现在,当在blazor中我需要发布数据时,我正在使用HttpClient,例如
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
}
我是否正确理解C#和异步方法?我的gui被冻结,直到发布结束,因为我要等待两次?如何在blazor webassembly中使用Http客户端在gui中发布数据和显示结果,而不必在发布数据和等待结果时冻结guid?
如果使用异步,应该不会有任何问题。JS和WebAssembly确实是单线程的,但这与使用
异步的能力无关。当您运行代码并使用wait关键字时,代码的执行将交给继续执行诸如重新呈现UI之类的操作的调用代码。当您的异步方法,比如PostAsJsonAsync返回时,当前方法的执行将继续。。。
当第二种方法,响应。所容纳之物ReadFromJsonAsync,再次被调用,执行权交给继续执行诸如重新呈现UI等操作的调用代码。
这是否意味着关于gui,ajax成功事件回调和等待在WebAssembly上的Httpclient中获得结果之间没有区别?
从某种意义上说是的。。。事实上,HttpClient服务的方法,如PostAsJsonAsync、GetAsJson异步,都是ajax调用,因为这些方法正在实现JavaScriptFetch-Api(在Blazor-webassembly中,对吧?(。
但这是C++。Net,而不是JavaScript。您的重点应该放在中异步的使用上。Net,如何使用它以及为什么使用它。我将使用默认模板的FetchData页面中的代码来演示它:
@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[]>
}
}
但是,在执行ajax调用时,这里启用并要求异步。异步是至关重要的,尤其是当您进行长时间调用时
您可以概括JavaScript中的回调、promise和async/await,它们类似于C#中的Task和async-await