0

I am trying create an alert message in within a Blazor component. I have no idea how to do this. I am running ASP.NET Core 3.1 Blazor server-side. Here's what I've tried

Component function:

private async Task ShowAlert() { await JSRuntime.InvokeAsync<object>("ShowMsg"); } 

Javascript Interop:

function ShowMsg() { success = "Success!"; return success; } 

File host.cshtml:

 <script src="~/BlazorInterop.js"></script> 
1

1 Answer 1

12
@page "/" <button @onclick="MessageBox">Show Message</button> @code { [Inject] IJSRuntime JSRuntime { get; set; } protected async Task MessageBox() { await JSRuntime.InvokeVoidAsync("exampleJsFunctions.ShowMsg", "Hello Blazor"); } } 

Put the following script tag beneath <script src="_framework/blazor.server.js"></script> in the _Host.cshtml file, like this:

<script src="_framework/blazor.server.js"></script> <script> window.exampleJsFunctions = { ShowMsg: function (message) { window.alert(message); } }; </script> 
1
  • 3
    Lot of magic strings. Is there a better way today?
    – cikatomo
    CommentedAug 5, 2023 at 17:48

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.