How do I show an alert message in a Blazor application?

If you want to show a message using a simple browser alert message box, it is easy to do in Blazor. In Blazor, you can call a JavaScript method using JavaScript interop.

In the following code snippets, the text entered in the text box will be displayed in the alert box. In order to call the JavaScript method in Blazor, you should register the method in the browser window class. You can pass the message you want to show by passing method parameters in the JSRuntime.InvokeAsync method.

[script.js]
window. Alert = function(message) {
           alert(message);
}

Refer the script file in the HTML page

[index.html/_Host.cshtml]
<head>
 .....
 <script src="~/script.js"></script>
 ....
</head>
[index.razor]

@page "/"

<input type="text" @bind="message" />
<button class="btn btn-primary" @onclick="Alert"> Alert Me!</button>

@code {

string message = "";

    private async Task Alert()
    {
        await JSRuntime.InvokeAsync<object>("Alert", message);
    }
}

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.