在Blazor中从JavaScript调用C#实例方法可以通过以下步骤实现:
public class MyInteropClass
{
public void MyMethod(string message)
{
// 在这里执行你的逻辑
Console.WriteLine(message);
}
}
@inject IJSRuntime JsRuntime
@code {
protected async override Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await JsRuntime.InvokeVoidAsync("registerInteropClass", new DotNetObjectRef(new MyInteropClass()));
}
}
}
window.registerInteropClass = function (interopClass) {
window.myInteropClass = interopClass;
};
function callCSharpMethod(message) {
window.myInteropClass.invokeMethodAsync('MyMethod', message);
}
这样,当用户点击按钮时,JavaScript将调用C#类的MyMethod
方法,并将消息传递给该方法。