javascriptc#htmlblazor

Blazor execute C# and JS function in one button onclick event


I have a button, which executes a JS function:

<button class="btn-orange btn" onclick="expand(this.closest('.profile'))">JavaScript</button>

And a button, which executes C# and switches icons depending on a bool:

<button class="btn-orange btn"
   @onclick="@(() =>
   {
      if (tempBool)
      {
         tempBool = !tempBool;
      }
      else
      {
         tempBool = true;
      }
   })">
   <i class="fa @(tempBool ? "fa-compress" : "fa-expand")" aria-hidden="true"></i>
</button>

How can I combine them?

I tried it with the OnClientClick Event, with JsRuntime.InvokeVoidAsync("expand(this.closest(.profile))");, or by putting both in the onclick event.

How can I execute a JavaScript function and C# in a button onclick event?

My JavaScript code I try to execute

EventPageExpandable.js:

function expand(card) {
    card.classList.toggle('profile--expanded');

    // If card is not expanded after toggle, add 'unexpanded' class
    if (!card.classList.contains('profile--expanded')) card.classList.toggle('profile--unexpanded');

    // Else if card is expanded after toggle and still contains 'unexpanded' class, remove 'unexpanded'
    else if (card.classList.contains('profile--expanded') && card.classList.contains('profile--unexpanded')) card.classList.toggle('profile--unexpanded');
}

How I tried to use JsRuntime:

await JsRuntime.InvokeVoidAsync("EventPageExpandable.expand", "this.closest('.profile')");

Or like this? But both doesn't work.

await JsRuntime.InvokeVoidAsync("expand", "this.closest('.profile')");```

Solution

  • Inject the JSRuntime:

    @inject IJSRuntime JsRuntime
    

    Bind the onclick event of the button:

    <button @onclick=ButtonClicked>Test</button>
    

    and execute the JavaScript function:

    private async Task ButtonClicked()
    {
        Console.WriteLine("From C#");
        await JsRuntime.InvokeVoidAsync("console.log", "From js");
    }
    

    When invoking JS-functions, pass the function name as first argument followed by all parameters