绑定变量未在用户界面中显示新值

时间:2020-07-12 20:50:01

标签: c# blazor blazor-server-side

我的页面上有以下代码:

@if (players == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <p>Number of Players: @players.Count</p>
    <p>Number of Teams: @teamsCount</p>
    <p>Excess Players: @excessPlayers</p>
}
@code {
    private List<PlayerModel> players;
    private int teamsCount { get; set; }
    private int excessPlayers { get; set; }

    protected override async Task OnInitializedAsync()
    {
        players = await _db.GetPlayers();

        int teamsCount = players.Count / 5;
        int excessPlayers = players.Count % 5;
    }

加载的html会正确显示一段时间,然后players.Count会正确更新并显示41,但是teamsCountexcessPlayers始终显示0。

我尝试在StateHasChanged()的结尾处致电OnInitializedAsync()

我还尝试了在单独的方法中设置teamsCountexcessPlayers并调用StateHasChanged()的方法,但这两个都不起作用。 teamsCountexcessPlayers仍然保持显示为0,尽管我在代码中看到它们分别是8和1,这是正确的。

我在做什么错了?

1 个答案:

答案 0 :(得分:2)

您正在通过teamsCount方法为excessPlayersOnInitializedAsync创建新的局部变量:

protected override async Task OnInitializedAsync()
{
    players = await _db.GetPlayers();

    int teamsCount = players.Count / 5;
    int excessPlayers = players.Count % 5;
}

您应该改为设置属性的值:

protected override async Task OnInitializedAsync()
{
    players = await _db.GetPlayers();

    teamsCount = players.Count / 5;
    excessPlayers = players.Count % 5;
}