0

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

1 Answer 1

1

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);
};
Sign up to request clarification or add additional context in comments.

13 Comments

ok thx. How come StateHasChanged() is needed in the JSInvokable? because it's coming from client I guess?
In the above case StateHasChanged() is not needed because StateHasChanged() method is automatically called after a UI event is triggered.
Also, you initiate on the button onclick, but I need to initiate via that JS function....so the javascript would be invokeJStoBlzr(objRef, "whatever");, but then how/when would the StartAsync method get called?
you can put the ``StartAsyc()` on OnAfterRenderAsync() method.
ya it works, thx
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.