Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

206
Views
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')");```
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!