【发布时间】:2020-10-20 13:58:07
【问题描述】:
我正在试验Blazor WebAssembly app。当我的页面(即 index.html)加载时,我想在加载时将一个 JavaScript 数组传递给 Blazor 应用程序。在尝试call a method from JavaScript 时,我遇到了一个错误,上面写着:
Uncaught (in promise) Error: No .NET call dispatcher has been set
我的代码如下所示:
index.html
<body>
<app>Loading...</app>
<div id="blazor-error-ui">
An unhandled error has occurred.
<a href="" class="reload">Reload</a>
<a class="dismiss">????</a>
</div>
<script src="_framework/blazor.webassembly.js"></script>
<script>
let items = [
{ name:'Item 1', description:'This is a description of the first item' },
{ name:'Item 2', description:'This is a description of the second item' },
{ name:'Item 3', description:'This is a description of the third item' },
];
try
{
DotNet
.invokeMethodAsync('MyOrg.MyApp.Index', 'LoadItems')
.then(results => {
console.log(results);
})
;
}
catch (ex)
{
console.log(ex);
}
</script>
</body>
Index.razor
@page "/"
@using System.Threading.Tasks;
@using Microsoft.Extensions.Logging;
@inject ILogger<Index> logger;
<p>
Items loaded: <span>@items.Count</span>
</p>
@code {
List<object> items = new List<object>();
[JSInvokable]
private Task LoadSnippets()
{
try
{
logger.LogInformation("Loading items...");
items = new List<object>();
}
catch (Exception ex)
{
logger.LogError(ex, $"Failed to load items.");
}
return Task.CompletedTask;
}
}
我注意到的第一个区别是文档中显示的示例依赖于static 方法。这是一个要求吗?如果是这样,那就意味着没有办法执行例如日志记录。撇开日志不谈,即使我将static 添加到LoadItems 方法中,我仍然会收到上面列出的错误。我不明白为什么。
简而言之,我正在尝试创建一个“无头”Blazor 应用程序。我想使用 C# 的丰富性来处理数据,我需要将结果传递给依赖于 HTML/CSS 的 UI。谢谢!
【问题讨论】: