Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor onclick event not triggered

Tags:

c#

onclick

blazor

I try to implement a simple onclick event handler like this sample https://blazorfiddle.com/s/counter but not working in my solution. The event is only triggered at the run of the web page for unknown reasons.

The HTML page with Blazor component is well show but when I click on the button, nothing is happening.

I'm on VS 2019 .Net Core 3.0. ASP.NET MVC project

Counter.razor file:

@using Microsoft.AspNetCore.Components

<p>Current count: @currentCount</p>

<button class="btn btn-primary" onclick="@IncrementCount();">Click me</button>

@code {
    int currentCount = 0;

    private async Task IncrementCount()
    {
        await Task.Run(() => currentCount++);
    }
}

Index.cshtml:

@using WebApplication2.Views.Components

@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

@(await Html.RenderComponentAsync<Counter>(RenderMode.Server, new { }))

startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();

    services.AddHttpClient();
    services.AddRazorPages();
    services.AddServerSideBlazor();
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
        endpoints.MapBlazorHub();
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

The button in browser :

<button class="btn btn-primary" onclick="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.Threading.Tasks.VoidTaskResult,WebApplication2.Views.Components.Counter+<IncrementCount>d__2];">Click me</button>

Error in browser:

Bug in brower

like image 253
micsp24 Avatar asked Oct 02 '19 07:10

micsp24


People also ask

How do you trigger click event in Blazor?

Blazor does not have support to manipulate DOM elements directly, but we can still achieve it by using JavaScript interop. By creating a reference to an element, we can send it as a parameter to the JavaScript method via interop.

What is EventCallback Blazor?

The EventCallback<T> class is a special Blazor class that can be exposed as a Parameter so that components can easily notify consumers when something of interest has occurred.

What is an EventCallback?

An event callback function is a function in a script that Monitoring Scripting Client calls in response to an event. In your event callback functions, provide code to generate statistics from the data in events. Typically, the following types of statistics can be generated from the data in events: Counter statistics.


1 Answers

This is the most popular question related to the problem: Blazor onclick events don't get triggered. Adding to the answers that resolved OP problem and were unable to resolve mine I would like to add that:

<script src="~/_framework/blazor.server.js"></script> need to be placed AFTER the component that declares the events, not in the <head /> tag. Possibly at the very bottom of the body tag of _Host.cshtml or your MVC View that needs Blazor components. If you don't do it, Blazor syntax will still work, the project WILL compile and most things WILL behave as expected but the events won't be triggered.

I just spent hours trying to figure that out.

Also if @onclick is not recognised as Blazor code in .razor files at all (this can happen especially in Component Libraries), make sure to add _Imports.razor at the very top of the project with the following content:

@using System.Net.Http
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.JSInterop

If for some reason some of the namespaces can't be found, they can be added as nuget packages.

like image 67
rvnlord Avatar answered Sep 30 '22 17:09

rvnlord