1)C#调用JS,需要依赖注入IJSRuntime(默认已经包含了),只能在组件或者页面中进行调用。
InvokeAsync<TValue>(String, Object[])异步调用指定的 JavaScript 函数,有返回值。
InvokeVoidAsync(String, Object[]) 异步调用指定的 JavaScript 函数,没有返回值。
2) JS调用C#
DotNet.invokeMethodAsync(...)
示例:
_Host.cshtml
@page "/"
@using Microsoft.AspNetCore.Components.Web
@namespace MyProject.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<base href="~/" />
<link rel="stylesheet" href="css/bootstrap/bootstrap.min.css" />
<link href="css/site.css" rel="stylesheet" />
<link href="MyProject.styles.css" rel="stylesheet" />
<link rel="icon" type="image/png" href="favicon.png"/>
<component type="typeof(HeadOutlet)" render-mode="ServerPrerendered" />
</head>
<body>
<component type="typeof(App)" render-mode="ServerPrerendered" />
<div id="blazor-error-ui">
<environment include="Staging,Production">
An error has occurred. This application may no longer respond until reloaded.
</environment>
<environment include="Development">
An unhandled exception has occurred. See browser dev tools for details.
</environment>
<a href="" class="reload">Reload</a>
<a class="dismiss">🗙</a>
</div>
<script src="_framework/blazor.server.js"></script>
<script>
async function InvokeCSharp()
{
await DotNet.invokeMethodAsync("MyProject", "Test", "小强!");
}
function showInfo(value)
{
document.getElementById("txtUserName").value = value;
}
</script>
</body>
</html>
Index.razor
@page "/"
<PageTitle>@UserName</PageTitle>
<div id="divUserName">
<input type="text" id="txtUserName" value="@UserName"/>
</div>
<button class="btn btn-primary" onclick="InvokeCSharp()">JS调用C#</button>
<button class="btn btn-primary" @onclick="InvokeJS">C#调用JS</button>
Index.razor.cs
using System.Diagnostics;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
namespace MyProject.Pages;
public partial class Index
{
private static Func<string,Task> TestAsync;
private string UserName{set;get;} = "小明";
[Inject]
private IJSRuntime JS{set;get;}
private async void InvokeJS()
{
await JS.InvokeVoidAsync("showInfo", "小红");
}
protected override void OnInitialized()
{
base.OnInitialized();
TestAsync = LocalTestAsync;
}
[JSInvokable]
public static async Task Test(string value)
{
await TestAsync.Invoke(value);
}
private async Task LocalTestAsync(string value)
{
if (UserName == "小明")
{
UserName = value;
}
else
{
UserName = "小明";
}
Console.WriteLine("UserName=" + UserName);
StateHasChanged();
}
}
结果:
