简体   繁体   中英

Blazor WAsm - Can't invoke JS function which returns a value

What I want to do
I want to call a JS function which returns a value. I did it exactly as documented here .

Setup
C#

Log.Warning("TESTESTESTTESTESTESTTESTESTEST");
await JsRuntime.InvokeAsync<bool>("UtilityTest.testFunc");
Log.Warning("TESTESTESTTESTESTESTTESTESTEST");

JS

var UtilityTest = new function () {
    this.testFunc = function () {
        console.log("[JS-TEST] testFunc");
        return true;
    };
};

Logs

TESTESTESTTESTESTESTTESTESTEST
[JS-TEST] testFunc
crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: An exception occurred executing JS interop: The JSON value could not be converted to System.Boolean. Path: $ | LineNumber: 0 | BytePositionInLine: 4.. See InnerException for more details.
Microsoft.JSInterop.JSException: An exception occurred executing JS interop: The JSON value could not be converted to System.Boolean. Path: $ | LineNumber: 0 | BytePositionInLine: 4.. See InnerException for more details. ---> System.Text.Json.JsonException: The JSON value could not be converted to System.Boolean. Path: $ | LineNumber: 0 | BytePositionInLine: 4. ---> System.InvalidOperationException: Cannot get the value of a token type 'Null' as a boolean.
  at System.Text.Json.Utf8JsonReader.GetBoolean () <0x2c89c00 + 0x00090> in <filename unknown>:0 
  at System.Text.Json.Serialization.Converters.JsonConverterBoolean.Read (System.Text.Json.Utf8JsonReader& reader, System.Type typeToConvert, System.Text.Json.JsonSerializerOptions options) <0x30ab220 + 0x00004> in <filename unknown>:0 
  at System.Text.Json.JsonPropertyInfoNotNullable`4[TClass,TDeclaredProperty,TRuntimeProperty,TConverter].OnRead (System.Text.Json.ReadStack& state, System.Text.Json.Utf8JsonReader& reader) <0x30a45a8 + 0x0003c> in <filename unknown>:0 
  at System.Text.Json.JsonPropertyInfo.Read (System.Text.Json.JsonTokenType tokenType, System.Text.Json.ReadStack& state, System.Text.Json.Utf8JsonReader& reader) <0x30a41d8 + 0x00088> in <filename unknown>:0 
  at System.Text.Json.JsonSerializer.HandleNull (System.Text.Json.Utf8JsonReader& reader, System.Text.Json.ReadStack& state) <0x30a3b58 + 0x00100> in <filename unknown>:0 
  at System.Text.Json.JsonSerializer.ReadCore (System.Text.Json.JsonSerializerOptions options, System.Text.Json.Utf8JsonReader& reader, System.Text.Json.ReadStack& readStack) <0x30a3218 + 0x0026a> in <filename unknown>:0 
   --- End of inner exception stack trace ---
  at System.Text.Json.ThrowHelper.ReThrowWithPath (System.Text.Json.ReadStack& readStack, System.Text.Json.Utf8JsonReader& reader, System.Exception ex) <0x30e4740 + 0x00028> in <filename unknown>:0 
  at System.Text.Json.JsonSerializer.ReadCore (System.Text.Json.JsonSerializerOptions options, System.Text.Json.Utf8JsonReader& reader, System.Text.Json.ReadStack& readStack) <0x30a3218 + 0x00320> in <filename unknown>:0 
  at System.Text.Json.JsonSerializer.ReadValueCore (System.Text.Json.JsonSerializerOptions options, System.Text.Json.Utf8JsonReader& reader, System.Text.Json.ReadStack& readStack) <0x309fe18 + 0x00592> in <filename unknown>:0 
  at System.Text.Json.JsonSerializer.ReadValueCore (System.Text.Json.Utf8JsonReader& reader, System.Type returnType, System.Text.Json.JsonSerializerOptions options) <0x309e998 + 0x0003e> in <filename unknown>:0 
  at System.Text.Json.JsonSerializer.Deserialize (System.Text.Json.Utf8JsonReader& reader, System.Type returnType, System.Text.Json.JsonSerializerOptions options) <0x309e830 + 0x00024> in <filename unknown>:0 
  at Microsoft.JSInterop.JSRuntime.EndInvokeJS (System.Int64 taskId, System.Boolean succeeded, System.Text.Json.Utf8JsonReader& jsonReader) <0x2c8a120 + 0x00052> in <filename unknown>:0 
   --- End of inner exception stack trace ---
  at System.Threading.Tasks.ValueTask`1[TResult].get_Result () <0x30f2538 + 0x00034> in <filename unknown>:0 
  at TestApp.Client.KeyboardManagerTest.Initialize () [0x0003d] in <Path>\Client\Test.cs:27 
  at TestApp.Client.Pages.TestPage.OnInitializedAsync () [0x00109] in <Path>\Client\Pages\TestPage.razor:49 
  at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync () <0x2ddec48 + 0x0013a> in <filename unknown>:0 
  at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask (System.Threading.Tasks.Task taskToHandle) <0x2f2fa10 + 0x000b6> in <filename unknown>:0

Direct JS call within the Browser's debug tools

UtilityTest.testFunc()
true

<Path>\Client\Test.cs:27 refers to the JsRuntime.InvokeAsync line. I really don't know why the exception is thrown ( JsRuntime.InvokeVoidAsync works). I hope someone can help me with this.

This code working for me


@page "/"

@inject IJSRuntime JsRuntime

<button class="btn btn-primary" @onclick="Test">Test</button>
@Result

@code
{
    private bool Result { get; set; } = false;
    private async Task Test()
    {
        Result = await JsRuntime.InvokeAsync<bool>("UtilityTest.testFunc");
    }
}

If you want to call your function when after component render you need to call in OnAfterRenderAsync

protected override async Task OnAfterRenderAsync(bool firstRender)
{
     if(firstRender)
     {
         await JsRuntime.InvokeAsync<bool>("UtilityTest.testFunc");
     }
     await base.OnAfterRenderAsync(firstRender);
}

You can check that source code for more Javascript for Blazor https://github.com/ShadyNagy/Blazor.JavaScriptUtilities

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM