I'm attempting to call a very simple js function from a razor script but it keeps throwing me the same error and I can't simply understand what's wrong.
This function is contained on a js script under wwwroot/js/jsScript.js
function showAlert(message) {
alert(message);
}
And I'm attempting to call it from 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");
}
}
As soon as I run my app it then crashes:
Browser's console errors:
Same errors in text:
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)
Any ideas as to why this is happening? I must be doing something really wrong.
This error indicates that IJSRuntime can not find the javascript function showAlert
, you could foget to add the reference in Pages/_Host.cshtml .
<script src="~/js/jsScript.js"></script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.