What are the differences between these two and which one should I use?
await JsRuntime.InvokeVoidAsync()
await JsRuntime.InvokeAsync()`
CodePudding user response:
InvokeVoidAsync
Use InvokeVoidAsync
when:
- .NET isn't required to read the result of a JavaScript (JS) call.
- JS functions return void(0)/void 0 or undefined.
For example the below function can call with InvokeVoidAsync
and doesn't return a value:
<script>
window.displayTickerAlert1 = (symbol, price) => {
alert(`${symbol}: $${price}!`);
};
</script>
And you can use this in a component by following code:
await JS.InvokeVoidAsync("displayTickerAlert1", stockSymbol, price);
InvokeAsync
Use InvokeAsync
when .NET should read the result of a JavaScript (JS) call.
The following example returns a string for display by the caller:
<script>
window.displayTickerAlert2 = (symbol, price) => {
if (price < 20) {
alert(`${symbol}: $${price}!`);
return "User alerted in the browser.";
} else {
return "User NOT alerted.";
}
};
</script>
And you can use of this to a component such as below:
var interopResult =
await JS.InvokeAsync<string>("displayTickerAlert2", stockSymbol, price);
result = $"Result of TickerChanged call for {stockSymbol} at "
$"{price.ToString("c")}: {interopResult}";
Please note that you have to inject IJSRuntime
on the above of the component, such as below:
@inject IJSRuntime JS
You can refer to Calling JavaScript from .NET and call-javascript-from-dotnet for more info.
CodePudding user response:
await JsRuntime.InvokeVoidAsync() executes Javascript function and this function do not return any value to C# code
await JsRuntime.InvokeAsync() also execute Javascript function but can return some value to C# code