最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

c# - Button click not triggering method in Blazor WebAssembly - Stack Overflow

matteradmin8PV0评论

I am working on a Blazor WebAssembly app in C# and I have a problem with a button click event. When I click the button, it should trigger the BuscarVehiculo method, but the method is not being called. I’ve tried using Console.WriteLine to debug, but the method never executes.

Here’s the code:

@page "/vehiculos"
@using System.Text.Json
@inject HttpClient Http
@using TallerModel

<h1>Vehículos</h1>

<!-- Campo de búsqueda -->
<input @bind="patente" placeholder="Ingresar patente del vehículo" />
<button @onclick="BuscarVehiculo">Buscar</button>

<!-- Botón para mostrar todas las patentes -->
<button @onclick="ToggleListaPatentes">
    @(mostrarListaPatentes ? "Ocultar todas las Patentes" : "Ver todas las Patentes")
</button>

<!-- Información del vehículo -->


<!-- Lista de patentes -->
@if (mostrarListaPatentes)
{
    <div class="mt-3">
        <h5>Lista de Patentes</h5>
        <ul>
            @foreach (var vehiculo in vehiculos)
            {
                <li>@vehiculo.Patente</li>
            }
        </ul>
    </div>
}

@code {
    private List<Vehiculo> vehiculos = new List<Vehiculo>
    {
        new Vehiculo { Patente = "ABC123", Marca = "Toyota", Modelo = "Corolla", Tipo = "Sedan", Chasis = "123456789", Motor = "987654321", DniApoderado = 12345678, NombreApoderado = "Juan Pérez" },
        new Vehiculo { Patente = "XYZ789", Marca = "Ford", Modelo = "Focus", Tipo = "Hatchback", Chasis = "987654321", Motor = "123456789", DniApoderado = 87654321, NombreApoderado = "Maria González" }
    };

    private Vehiculo? vehiculoEncontrado;
    private string? patente;
    private bool buscarRealizado = false;
    private bool mostrarListaPatentes = false;

    // Método para buscar un vehículo por patente
    private void BuscarVehiculo()
    {
        Console.WriteLine($"Buscando vehículo con patente: {patente}");
        buscarRealizado = true;

        if (string.IsNullOrEmpty(patente))
        {
            Console.WriteLine("La patente no puede estar vacía.");
            return;
        }

        // Inicializamos la variable en null antes de buscar
        vehiculoEncontrado = null;

        // Verificar si la lista de vehículos está cargada
        if (vehiculos == null || !vehiculos.Any())
        {
            Console.WriteLine("La lista de vehículos está vacía.");
            return;
        }

        // Buscar el vehículo por patente
        foreach (var vehiculo in vehiculos)
        {
            Console.WriteLine($"Revisando vehículo con patente: {vehiculo.Patente}");
            if (vehiculo.Patente.Equals(patente, StringComparison.OrdinalIgnoreCase))
            {
                Console.WriteLine($"Vehículo encontrado: {vehiculo.Patente}");
                vehiculoEncontrado = vehiculo;
                break; // Terminamos la búsqueda al encontrar el vehículo
            }
        }

        if (vehiculoEncontrado == null)
        {
            Console.WriteLine("No se encontró el vehículo.");
        }

        StateHasChanged(); // Fuerza la actualización de la UI
    }
}

When I click the "Buscar" button, it should call the BuscarVehiculo method, but the method is never triggered. I’ve checked the console for any output, but it doesn’t log anything from the BuscarVehiculo method. The rest of the Blazor components, like binding the patente input field, work fine.

Steps I’ve tried:

  • I’ve checked that the @onclick event is properly bound to the method.
  • I’ve added a Console.WriteLine in the method to check if it’s being called, but nothing is printed when the button is clicked.
  • I have verified the vehiculos list is populated properly.

Can anyone help me understand why the @onclick event is not triggering the BuscarVehiculo method?

Post a comment

comment list (0)

  1. No comments so far