Home > Software engineering >  How to send from javascript to javascript .NET instance function in Blazor? (jsinterop, invokeMethod
How to send from javascript to javascript .NET instance function in Blazor? (jsinterop, invokeMethod

Time:12-09

I have some javascript where I need to send a value to a javascript function that calls .NET function via invokeMethodAsync

so the simple javascript code to send value something like:

invokeJStoBlzr("sfsd");

then the JS function...

window.invokeJStoBlzr(val) = (dotNetHelper) => {            
  dotNetHelper.invokeMethodAsync('JStoSrvCall', val);
};

but it doesn't seem to like window.invokeJStoBlzr(val) so I think it's a matter of syntax. Anyone know how to properly write that?

Blazor code is

private DotNetObjectReference<Index> objRef;


public async Task startAsyc()    {   //called when client side makes selection
   await JsRuntime.InvokeAsync<string>("invokeJStoBlzr", objRef);
}

[JSInvokable]
protected static void JStoSrvCall(string value)
{
  //do whatever
}

I basically need to pass a javascript value to that invokeJStoBlzr function, which then is received in JStoSrvCall

CodePudding user response:

I basically need to pass a javascript value to that invokeJStoBlzr function, which then is received in JStoSrvCall

If you want to pass a value from JavaScript to C# then you could do something like this:

<button @onclick="() => StartAsyc()">Start</button>
<h1>@JSMessage</h1>

@code{
    private string JSMessage { get; set; }

    public async Task StartAsyc()
    {   //called when client side makes selection
        await JsRuntime.InvokeVoidAsync("invokeJStoBlzr", DotNetObjectReference.Create(this),
            "The Value You want to Send to JS");
    }

    [JSInvokable]
    public void JStoSrvCall(string value)
    {
        JSMessage = value;
        StateHasChanged();
    }
}

and JavaScript code will look like this:

function invokeJStoBlzr(instance, val) {
    instance.invokeMethodAsync('JStoSrvCall', val);
};
  • Related