3

I have an app that uses a jQuery lib to show 'confirmation' dialogs.

When a user clicks 'OK' or 'Cancel' on the dialog, then first a callback is made to my Javascript code. From there I do a call to a Blazor method, based on the decision the user made.

This all looks something like this:

My js code:

$('.alert-yesno).on('click', function() {
    // For simplicity I immediately call the Blazor method
    DotNet.invokeMethodAsync('[Assembly name]', 'DoSomething')
                            .then(data => {
                                // do something...
                            });
});

Blazor page:

@inject MyService MyService

<button class="alert-yesno">Show dialog</button>

@code
{
    [JSInvokable]
    public static async Task DoSomething()
    {
        // How to use the non static MyService here...?
    }
}

This all works fine. The Javascript part calls my Blazor method. But how can I use MyService from there? This is injected into the page. Which is good, because it makes use of dependency injection.

I don't want to create a new instance everytime from within the static method, because that way I loose all the auto injected dependencies.

How can I solve this issue?

1 Answer 1

2

See https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interop?view=aspnetcore-3.0#instance-method-call for a more complete example, but you can pass a reference to the the .net instance to the javascript code by calling

DotNetObjectReference.Create(myInstance);

Then the javascript code can call the instance method on that object. Since the component (and thus the service which is injected into it) has a potentially different lifespan than the jquery click handler, this might cause some other issues, but the link above should be a good starting point.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.