Blazor Web UI does not get updated for one variable - Stack Overflow

admin2025-04-17  4

Very new to Blazor, trying to create a simple form where the button updates text on the UI when clicked. I am changing the existing Weather page.

The form:

<form action="" method="post" @formname="main">
    <InputText @bind-Value="ApiKey" type="password" @onchange="PasswordUpdated" size="60"/>
    <Button Type="submit" Color="ButtonColor.Primary" To="#" @onclick="ValidateClicked"> Submit </Button>
    <AntiforgeryToken/>
</form>

Only added a <p> on top of the table below:

@if (forecasts == null)
{
    <p>
        <em>Processing...</em>
    </p>
}
else
{
    <p>Result: @response.Response</p>
    <table class="table">
        <thead>
        <tr>
            <th>Date</th>
            <th aria-label="Temperature in Celsius">Temp. (C)</th>
            <th aria-label="Temperature in Farenheit">Temp. (F)</th>
            <th>Summary</th>
        </tr>
        </thead>
        <tbody>
        @foreach (var forecast in forecasts)
        {
            <tr>
                <td>@forecast.Date.ToShortDateString()</td>
                <td>@forecast.TemperatureC</td>
                <td>@forecast.TemperatureF</td>
                <td>@forecast.Summary</td>
            </tr>
        }
        </tbody>
    </table>
}

Setting the field in OnInitializedAsync just works fine.

protected override async Task OnInitializedAsync()
    {
        // Simulate asynchronous loading to demonstrate streaming rendering
        await Task.Delay(500);

        var startDate = DateOnly.FromDateTime(DateTime.Now);
        var summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" };
        forecasts = Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = startDate.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = summaries[Random.Shared.Next(summaries.Length)]
        }).ToArray();
        response = new ResponseModel() { Response = "Starting..." };
    }

However, when I click the button, although the weather forecast is updated, response stays unchanged.

   private async void ValidateClicked()
    {
        await Task.Delay(1000);
        response.Response = "Validating...";
        var startDate = DateOnly.FromDateTime(DateTime.Now);
        var summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" };
        forecasts = Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = startDate.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = summaries[Random.Shared.Next(summaries.Length)]
        }).ToArray();
转载请注明原文地址:http://anycun.com/QandA/1744821961a88091.html