Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

Onclick event not working in Blazor Web Assembly 8.0

$
0
0

I am studying a Blazor course and I noticed the button click event does not trigger on button click. I created a simple Blazor web assembly 8.0 project to confirm the issue. I noticed on button click nothing happened.

I added @rendermode InteractiveServer to my test page and also these methods to my program.cs, but nothing happened.

builder.Services.AddRazorComponents().AddInteractiveServerComponents()app.MapRazorComponents<App>().AddInteractiveServerRenderMode();

Program.cs

using BlazorApp1.Components;var builder = WebApplication.CreateBuilder(args);builder.Services.AddRazorComponents();builder.Services.AddRazorComponents().AddInteractiveServerComponents();var app = builder.Build();if (!app.Environment.IsDevelopment()){  app.UseExceptionHandler("/Error", createScopeForErrors: true);  app.UseHsts();}app.MapRazorComponents<App>().AddInteractiveServerRenderMode();app.UseHttpsRedirection();app.UseStaticFiles();app.UseAntiforgery();app.MapRazorComponents<App>();app.Run();

Test.razor

@page "/test"@rendermode InteractiveServer@inject IJSRuntime JsRuntime<h3>Test JavaScript Interop</h3><button type="button" @onclick="TestJsInterop">Click Me</button>@code {  private async Task TestJsInterop()  {    // Call the custom JS function showCustomAlert    await JsRuntime.InvokeVoidAsync("showCustomAlert", "Hello from custom JS interop!");  }}
window.showCustomAlert = function (message) {  alert(message); // This is the native JS alert function}

index.html

<!DOCTYPE html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>BlazorApp</title><base href="/" /><link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" /><link href="css/site.css" rel="stylesheet" /></head><body><app><!-- The component rendered in InteractiveServer mode will be mounted here --></app><script src="_framework/blazor.server.js"></script><script src="js/spp.js"></script></body></html>

The weird part is that the counter button works perfectly well in the counter page.

I also Updated Routes element in App.razor file with <Routes @rendermode=RenderMode.InteractiveServer /> and <script src="_framework/blazor.web.js"></script>

I want the button click event to display an alert with message "Hello from custom JS interop!"

Please help me fix this error as I can't forge ahead with my Blazor tutorial.


Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>