Blazor JS interop: how to pass undefined to a JavaScript function

Viewed 729

In a blazor project a JavaScript function distinguishes between null and undefined. When passing null from C# (await jsRuntime.InvokeAsync<long>("func", null, "str")) the JS side receives value null (typeof arg1 === 'object'). What to pass from C# side to receive undefined (typeof arg1 === 'undefined')?

Edit: Apparently the behavior of null is not consistent, it depends on the position of the argument. JS:

        func1: function (arg1) {
            console.log("func1", typeof arg1);
        },
        func2: function (arg1, arg2) {
            console.log("func2", typeof arg1);
        },

C#:

        await jsRuntime.InvokeVoidAsync("utils.func1", null);
        await jsRuntime.InvokeVoidAsync("utils.func1");
        await jsRuntime.InvokeVoidAsync("utils.func1", "aaa");
        await jsRuntime.InvokeVoidAsync("utils.func2", null, 123);
        await jsRuntime.InvokeVoidAsync("utils.func2", "aaa", 123);

Output:

func1 undefined
func1 undefined
func1 string
func2 object
func2 string
1 Answers

If you want to know if you send an argument or if null in the javascript function you can use ===undefined or ===null.

<script>
    var func1=(arg1)=> {
        console.log("func1", arg1,arg1===null,arg1===undefined,typeof arg1);
    }
</script>

but you need send "null explicity"

    var data = (string)null; //<--I check with this
    await JSRuntime.InvokeAsync<string>("func1","Hello world");
    await JSRuntime.InvokeAsync<string>("func1", data);
    await JSRuntime.InvokeAsync<string>("func1");
Related