Search code examples
c#componentsblazorblazor-server-sideblazor-client-side

Blazor Child Component EventCallBack not responding


Here Page Component

@page "/student"
<h3>Student List</h3>
<h5>@StudentsList</h5>

<StudentDetail StudentName="Something New" ButtonClicked="@Save"></StudentDetail>

<h5>This is second</h5>
<h5>@SaveMessage</h5>


@code {
    public string StudentsList { get; set; }
    private string SaveMessage { get; set; }

    protected override async Task OnInitializedAsync()
    {
        StudentsList = "ASD DSA KDS CFA";
    }

    private void Save(MouseEventArgs e)
    {
        SaveMessage = "Operation Saved.";
    }
}

And this is the StudentDetail

<h3>Student Detail for @StudentName</h3>
<button class="btn btn-primary" @onClick="ButtonClicked">Click Me!</button>
@code {
    [Parameter]
    public string StudentName { get; set; }

    [Parameter]
    public EventCallback<MouseEventArgs> ButtonClicked { get; set; }

}

I tried this on both Server and Client sides. When i click the "Click Me!" button, absolutely nothing happens. What am i doing wrong?

These are imports

@using System.Net.Http
@using System.Net.Http.Json
@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
@using BlazorApp4
@using BlazorApp4.Shared

Solution

  • StudentDetail:

    It's @onclick, not @onClick in @onClick="ButtonClicked"

    When you click on the "Click Me!" button, you actually want to trigger the "Save" method in the Student component. This is how you do that:

    `@onclick="() => ButtonClicked.InvokeAsync()"`
    

    Student: Change ButtonClicked="@Save" to ButtonClicked="Save"