幽梦紫曦

Blazor的c#调用JavaScript传参

电脑版发表于:2021/12/13 14:07
1、新建类库ExampleMethed和BlazorMerhed
private string name = "张三";
private string result = string.Empty;
private BlazorMerhed merhed;
private DotNetObjectReference<ExampleMethed> reference;
private async Task TriggerMethod()
{
      //两张方法结果一样
   //merhed = new BlazorMerhed(JSRuntime);
   //result = await merhed.CallHelloHelperGetHelloMessage(name);
    reference = DotNetObjectReference.Create(new ExampleMethed(name));
    result = await JSRuntime.InvokeAsync<string>("TriggerMethod", reference);
}
public void Dispose()
{
   merhed?.Dispose();
}
public class BlazorMerhed : IDisposable
{
   private readonly IJSRuntime _JSRuntime;
   private DotNetObjectReference<ExampleMethed> reference;
   public BlazorMerhed(IJSRuntime JSRuntime)
   {
       _JSRuntime = JSRuntime;
   }
   public ValueTask<string> CallHelloHelperGetHelloMessage(string name)
   {
       reference = DotNetObjectReference.Create(new ExampleMethed(name));
       var message = _JSRuntime.InvokeAsync<string>("TriggerMethod", reference);
       return message;
    }
    public void Dispose()
    {
       reference?.Dispose();
    }
}
public class ExampleMethed
{
    public string Name { get; set; }
    public ExampleMethed(string name)
    {
       Name = name;
    }
       [JSInvokable]
       public string GetHelloMessage() => $"Hello, {Name}!";
    }
window.TriggerMethod = (dotNetHelper) => 
{
   return dotNetHelper.invokeMethodAsync('GetHelloMessage');
};

关于TNBLOG
TNBLOG,技术分享。技术交流:群号677373950
ICP备案 :渝ICP备18016597号-1
App store Android
精彩评论
{{item.replyName}}
{{item.content}}
{{item.time}}
{{subpj.replyName}}
@{{subpj.beReplyName}}{{subpj.content}}
{{subpj.time}}
猜你喜欢