Search code examples
razorblazor.net-8.0

Blazor tutorial: @onclick event doesn't work in new razor components


I am very new to Blazor, and I'm following the blazor-workshop tutorial.

I'm on .NET version 8.0.100

I created the sample project with the counter component, played a bit with that and everything I tested worked correctly (like displaying a number of emojis corresponding to the counter value thanks to a for loop, that kind of basic things).

I went to the next step with the exercise on building a todo list.

I followed the guide step by step, have the exact same code (step 4), but clicking the "Add todo" button doesn't do anything.

My Todo.razor component:

@page "/todo"

<h3>Todo</h3>

<ul>
    @foreach(var todo in todos)
    {
        <li>@todo.Title</li>
    }
</ul>

<input placeholder="Something to do" @bind="newTodo" />
<button @onclick="AddTodo">Add</button>

@code {
    private List<TodoItem> todos = new();
    private string? newTodo;

    private void AddTodo()
    {
        if (!string.IsNullOrWhiteSpace(newTodo))
        {
            todos.Add(new TodoItem{Title = newTodo});
            newTodo = string.Empty;
        }
    }
}

I tried to debug it in VS Code: I added a breakpoint at the beginning of the "AddTodo()" method, and it turns out the method is not reached when I click the button.

I tried to replace the content of the "Counter.razor" component (which is created when the new blazor project is created) with the content of the "Todo.razor" component, and here everything works fine: items are added to the list when I click the button.

Does anyone know what I'm doing wrong here?

Thanks!!

EDIT: I was missing the @rendermode InteractiveServer line at the top of my component. That solve the thing! But I don't see the green mark for marking ℍ ℍ's answer as correct.


Solution

  • From .NET 8 they've introduced Render modes MS docs

    It's a feature that you will need to learn and actively incorporate into .NET 8 Blazor projects for interactive components. To enable interactivity in components each component will need a @rendermode declared either locally or globally.

    However, if you want to follow that tutorial I recommend you learn using the version it was designed for. Here's how you create a Blazor app with a .NET version of <= 7 using the CLI.

    //server side Blazor
    dotnet new blazorserver -f net7.0 -o BlazorApp
    
    //client side Blazor
    dotnet new blazorwasm -f net7.0 -o BlazorApp