Search code examples
javascriptblazorblazor-webassembly

Passing Arrays to blazors IJSRuntime.InvokeAsync


I wonder what is the best way to pass an array to IJSRuntime.InvokeAsync.
The problem I stumbled upon is that blazor will pass each element of the array as a parameter to the javascript function since InvokeAsync has an open parameter list and will not know if you just passed arguments of the same type or an array.

For now I just go with a second parameter like InvokeAsync("functionname", array, false).

Any other suggestions? Better solutions?


Solution

  • You'd either have to cast your array to object* or call the Extension method directly:

    var array = Array.Empty<Baz>();
    // Casting to object
    JS.InvokeAsync<Foo>("bar", (object)array);
    
    // Explicitly call the extension method:
    JSRuntimeExtensions.InvokeAsync<Foo>(JS, "bar", array);
    

    Or just use the overload it thinks you are attempting to call:

    JS.InvokeAsync<Foo>("bar", new object[] { array });
    

    * Based on my limited knowledge of C#'s Overload Resolution.