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

13
@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>
Sign up to request clarification or add additional context in comments.

1 Comment

Lot of magic strings. Is there a better way today?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.