tnblog
首页
视频
资源
登录

Blazor的c#调用JavaScript传参

5272人阅读 2021/12/13 14:07 总访问:342466 评论:0 收藏:0 手机
分类: ASP.NET
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');
};

评价
当你知道迷惑时,并不可怜,当你不知道迷惑时,才是最可怜的。
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
欢迎加群交流技术