简体   繁体   中英

JS in blazor component

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>
    
@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>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM