blazorblazor-jsinterop

How to use [JSInvokable] on event callback


I followed first example in this link. https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/call-dotnet-from-javascript?view=aspnetcore-6.0

Min and max values are passed onclick from NavBar.razor -> index.js file, when "CalculateMinMax " button is clicked. My aim is to get min and max values to be printed in console.log() of index.js.

  1. How do I use[JSInvokable] for '_modal'(button click of CalculateMinMax)? Since it isn't a regular function but a event call back.

Interop works, when I try calling [JSInvokable] on 'ReturnArrayAsync'. I am not sure how to use [JSInvokable] for '_modal'. Thank you.

NavBar.razor:

<li class="dropdown-item">
    <button id="btn" @onclick="() => _modal.Open()">CalculateMinMax</button>
</li>

        <Modal @ref="_modal" OnDoneCallback1="OnModalMin" OnDoneCallback2="OnModalMax" />

        @code {

            private Modal _modal { get; set; }
            public static string _min;
            public static string _max;

            private void OnModalMin(string min)
            {
                _min = min;
            }

            private void OnModalMax(string max)
            {
                _max = max;
                ReturnArrayAsync();
            }

            [JSInvokable]  // 'ReturnArrayAsync' works when called, but I need to call '_modal'
            public static Task ReturnArrayAsync()
            {
                var min = @_min;
                var max = @_max;
                return Task.FromResult(new string[] { min, max });
                Console.WriteLine("return min", min);

            }

        }

Index.js:

$("#btn").click(function () {
             DotNet.invokeMethodAsync('AssemblyName', '_modal') // works for ''ReturnArrayAsync' but not sure how to incorporate for _modal.
             .then(data => {
             console.log(data);  // print max min value here                             
             });                         
 });

Solution

  • Inside index.js add a function that you will call from blazor component.

    window.printMinMax = function (min, max) {
        console.log("min = " + min + ", max = " + max);
    }
    

    You need to add a new EventCallback to your Modal component when it closes. Then inject IJSRuntime to your component to pass min and max to js function.

    @inject IJSRuntime JS
    
    <Modal @ref="_modal" OnClose="ModalClosed" OnDoneCallback1="OnModalMin" OnDoneCallback2="OnModalMax" />
    
    @code {
        // when modal closes both min and max have been set by user so we send values to javascript function
        private async Task ModalClosed()
        {
            await JS.InvokeVoidAsync("printMinMax", _min, _max);
        }
    }
    

    https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/call-javascript-from-dotnet?view=aspnetcore-6.0