Blazor JSInterop static vs instance C# methods

353 views Asked by At

Could somebody please let me know how static methods work in regard to calling C# methods from JavaScript using JS interop?

If I have a static method in the code section of a component that references objects in that component, and there are multiple instances of that component on a page, will all instances be affected by the method call?

Or even worse, will this act as a Singleton on my server causing updates to every single client instance of that component?

I'm currently developing an audio recording system that cycles through phrases marked in text, and whenever JavaScript detects 5 frames of silence in the media stream, I want to call a C# method that will highlight the next section of text by changing its CSS class.

1

There are 1 answers

1
Dylan El Bar On BEST ANSWER

If you want to change some styles in your component, you definitely not want to use a static method. Because a static method could not interact with the instance of the component - as you cannot use the this keyword in a static method.

What I think you want to do is first, in C# side, create a classic method in your component C# code. For example create:

public void ChangeStyle() 
{
     this.ClassToDisplay = DoSomeManipulation();
}

Then, JS will need the instance of the the component. So you can do something like that: (I use the OnAfterRenderAsync because it is shown in Microsoft documentation, but the goal is to do it once)

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        DotNetObjectReference<MyComponent>? dotNetHelper = DotNetObjectReference.Create(this);
        await JS.InvokeVoidAsync("JSFile.setDotNetHelper", dotNetHelper);
    }
}

Then in JS side, you will need the setDotNetHelper method, with the following content:

class JSFile
{
    static dotNetHelper;

    static setDotNetHelper(value)
    {
        JSFile.dotNetHelper = value;
    }
}

Now you are ready, you can call whenever you want the ChangeStyle method of your component. To do so, use this instruction in JS:

await dotNetHelper.invokeMethodAsync('ChangeStyle');

Et voilĂ . I am available for clarifications or questions, have a good one!

// Dylan