Blazor WebAssembly中C#与JS之间互相调用

目录

  • 1首先在razor中引入“IJSRuntime JSRuntime”
  • 2JS代码
  • 3 C#调用JS函数
  • 4 JS调用C#函数

1首先在razor中引入“IJSRuntime JSRuntime”

2JS代码

window.FParam = {
			CObject: null,
			init: function (obj) {
				this.CObject = obj;
			},
			alert: function (...param) {
				//let bMsg = param1 + param2 + param3;
				let bMsg = '';
				for (let msg of param) {
					bMsg += msg;
				}
				
				alert(bMsg);
			},
		};

		
		function SelfAlert(...param) {
			let bMsg = '';
			for (let msg of param) {
				bMsg += msg;
			}

			alert(bMsg);
		}

3 C#调用JS函数

	//第一参数为函数名,后面的为函数参数,可以使用Rest参数、多个参数
	JSRuntime.InvokeVoidAsync("FParam.alert","你好!","Bob,","吃了吗?");
    JSRuntime.InvokeVoidAsync("SelfAlert","你好!","Bob,","吃了吗");

4 JS调用C#函数

//首先在razor界面中,将界面对象传给JS
protected override async Task OnInitializedAsync()
  {
    await JSRuntime.InvokeVoidAsync("FParam.init", DotNetObjectReference.Create(this));
  }

//JS需要调用的方法
  [JSInvokable]
  public void ChangeYzm()
  {
    Yzm = "123";
    this.StateHasChanged();
  }

JS调用方式

//第一个参数是函数名,后面的为函数参数
this.CObject.invokeMethodAsync("ChangeYzm");

你可能感兴趣的:(wasm,c#,javascript)