Tengo un botón que ejecuta una función JS:
<button class="btn-orange btn" onclick="expand(this.closest('.profile'))">JavaScript</button>Y un botón, que ejecuta C# y cambia de ícono dependiendo de un 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>¿Cómo puedo combinarlos?
Lo probé con el evento OnClientClick , con JsRuntime.InvokeVoidAsync("expand(this.closest(.profile))"); , o colocando ambos en el evento onclick.
¿Cómo puedo ejecutar una función de JavaScript y C# en un evento de botón al hacer clic?
Mi código JavaScript que trato de ejecutar
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'); }Cómo traté de usar JsRuntime:
await JsRuntime.InvokeVoidAsync("EventPageExpandable.expand", "this.closest('.profile')");¿O así? Pero ambos no funcionan.
await JsRuntime.InvokeVoidAsync("expand", "this.closest('.profile')");```Inyecte el JSRuntime:
@inject IJSRuntime JsRuntimeEnlace el evento onclick del botón:
<button @onclick=ButtonClicked>Test</button>y ejecuta la función JavaScript:
private async Task ButtonClicked() { Console.WriteLine("From C#"); await JsRuntime.InvokeVoidAsync("console.log", "From js"); }Al invocar funciones JS, pase el nombre de la función como primer argumento seguido de todos los parámetros