【发布时间】:2021-02-09 00:48:54
【问题描述】:
我正在尝试从 razor 脚本调用一个非常简单的 js 函数,但它不断向我抛出同样的错误,我无法简单地理解出了什么问题。
此函数包含在 wwwroot/js/jsScript.js 下的 js 脚本中
function showAlert(message) {
alert(message);
}
我正在尝试从 MyPage.razor 调用它
@{
<button type="button" class="btn btn-info" @onclick="ShowAlertWindow">Show Alert Window</button>
}
@code {
protected async Task ShowAlertWindow()
{
//IJSRuntime.InvokeAsync<string>("console.log", "ShowAlertWindow");
await IJSRuntime.InvokeVoidAsync("showAlert", "JS function called from .NET");
}
}
只要我运行我的应用程序,它就会崩溃:
浏览器的控制台错误:
文本中的相同错误:
Failed to load resource: the server responded with a status of jsScript.js:1 404 ()
blazor.server.js:19 [2021-02-09T00:29:40.323Z] Error: Microsoft.JSInterop.JSException: Could not find 'showAlert' in 'window'.
Error: Could not find 'showAlert' in 'window'.
at https://localhost:44379/_framework/blazor.server.js:8:30944
at Array.forEach (<anonymous>)
at p (https://localhost:44379/_framework/blazor.server.js:8:30904)
at https://localhost:44379/_framework/blazor.server.js:8:31614
at new Promise (<anonymous>)
at e.beginInvokeJSFromDotNet (https://localhost:44379/_framework/blazor.server.js:8:31587)
at https://localhost:44379/_framework/blazor.server.js:1:20052
at Array.forEach (<anonymous>)
at e.invokeClientMethod (https://localhost:44379/_framework/blazor.server.js:1:20022)
at e.processIncomingData (https://localhost:44379/_framework/blazor.server.js:1:18006)
at Microsoft.JSInterop.JSRuntime.InvokeWithDefaultCancellation[T](String identifier, Object[] args)
at Microsoft.JSInterop.JSRuntimeExtensions.InvokeVoidAsync(IJSRuntime jsRuntime, String identifier, Object[] args)
at FIS.IO.Pages.Index.ShowAlertWindow() in C:\Users\tfaon\source\repos\FIS.IO\FIS.IO\Pages\Index.razor:line 27
at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle)
关于为什么会发生这种情况的任何想法?我一定是做错了什么。
【问题讨论】:
-
您是否注册了包含 showAlert 功能的脚本文件?
-
是的,在 Pages/_Host.cshtml 文件中。
标签: javascript c# asp.net-core blazor