Ber*_*ian 4 interop promise blazor
我正在通过 js 互操作向服务器发出POST
请求Blazor
。发布请求到达服务器,进行计算,然后发回。处理程序js
调用resolve
Promise,但数据不会返回到Blazor
。
JS 互操作
window.methods={
submit: function () {
return new Promise((resolve, reject) => {
var form = document.getElementById("newTestForm");
var data = new FormData(form);
var xhr = new XMLHttpRequest();
var method = form.getAttribute('method');
var action = form.getAttribute('action');
xhr.open(method, action);
xhr.onload = function () {
if (xhr.status == 200) {
resolve(xhr.response); //data gets here in correct format !!!!!!!
}
else if (xhr.status != 200) {
reject("Failed to submit form with status" + xhr.status);
}
}
xhr.send(data);
});
}
}
Run Code Online (Sandbox Code Playgroud)
控制器
[HttpPost]
[Route("/myroute")]
public async Task<string> ReturnData()
{
await Task.Delay(1000);
return "hello";
}
Run Code Online (Sandbox Code Playgroud)
Blazor 组件
<form method="post" action="/myroute">
....some inputs
</form>
<button onclick="@SubmitAsync"></button>
@functions{
public static async Task<string> SubmitNewTestAsync()
{
try
{
var data = await JSRuntime.Current.InvokeAsync<string>("methods.submit");
return data;
}
catch (Exception ex)
{
throw;
}
}
public async Task SubmitAsync()
{
string data= await SubmitNewTestAsync();
}
}
Run Code Online (Sandbox Code Playgroud)
响应正确,js方法submit
调用resolve
结果。我首先认为这可能是反序列化问题。但它不会引发任何错误。
我尝试过不同类型的响应(bytes
、objects
、string
),但仍然没有响应或异常。
问题可能是什么?
PS 我需要使用,XMLHttpRequest
因为我想留在同一页面上。如果 Blazor 中存在异常,我应该会看到异常,因为我正在使用进行测试Server-Side hosting
更新
好吧,在尝试了很多事情之后,问题似乎出在方法Blazor
上JSRuntime.Current.InvokeAsync<Type>
。
看来请求将完成而不返回任何内容(也不会抛出任何错误),除非Type
//primitive
我object
现在dynamic.
不知道这是否是一个Blazor
特定的问题了。
例子
考虑以下模型:
[Serializeable]
public class MyType{
public int value{get;set;}
}
Run Code Online (Sandbox Code Playgroud)
所以这就是发生的情况(Blazor 方面):
var data = await JSRuntime.Current.InvokeAsync<MyType>("methods.submit"); //fails
var data = await JSRuntime.Current.InvokeAsync<object>("methods.submit"); //works
var data = await JSRuntime.Current.InvokeAsync<dynamic>("methods.submit"); //works
Run Code Online (Sandbox Code Playgroud)
到目前为止,还使用 和 进行了测试long
,int
并且string
它们有效。看来接收原语没有问题。
这可能是使用已删除的静态 JSRuntime.Current 属性的结果。相反,您应该将 IJSRuntime 注入到您的组件中:
@注入 IJSRuntime JSRuntime;
public static async Task<string> SubmitNewTestAsync()
{
try
{
var data = await JSRuntime.InvokeAsync<string>("methods.submit");
return data;
}
catch (Exception ex)
{
throw;
}
}
Run Code Online (Sandbox Code Playgroud)
在 JavaScript 函数中尝试以下代码片段:
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(xhr.responseText);
} else {
reject("Failed to submit form with status" + xhr.status);
}
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3819 次 |
最近记录: |