【问题标题】:JS in blazor componentBlazor 组件中的 JS
【发布时间】:2020-11-22 08:48:18
【问题描述】:
我正在尝试在 Blazor 组件中创建警报消息。我不知道该怎么做。我正在运行 ASP.NET Core 3.1 Blazor 服务器端。这是我尝试过的方法
组件功能:
private async Task ShowAlert()
{
await JSRuntime.InvokeAsync<object>("ShowMsg");
}
Javascript 互操作:
function ShowMsg() {
success = "Success!";
return success;
}
文件host.cshtml:
<script src="~/BlazorInterop.js"></script>
【问题讨论】:
标签:
javascript
c#
asp.net-core
blazor
【解决方案1】:
@page "/"
<button @onclick="MessageBox">Show Message</button>
@code
{
[Inject] IJSRuntime JSRuntime { get; set; }
protected async Task MessageBox()
{
await JSRuntime.InvokeVoidAsync("exampleJsFunctions.ShowMsg",
"Hello Blazor");
}
}
在_Host.cshtml 文件中的<script src="_framework/blazor.server.js"></script> 下放置以下脚本标记,如下所示:
<script src="_framework/blazor.server.js"></script>
<script>
window.exampleJsFunctions =
{
ShowMsg: function (message) {
window.alert(message);
}
};
</script>