Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

207
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda