绑定变量未在UI中显示新值



我的页面中有以下代码:

@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。

我试着在OnInitializedAsync()结束时呼叫StateHasChanged()

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

我做错了什么?

您正在OnInitializedAsync方法中为teamsCountexcessPlayers创建新的局部变量:

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;
}

相关内容

  • 没有找到相关文章

最新更新