blazor WASM新的选择选项刷新速度慢于新绑定值的分配



我有一个选择下拉列表,通过列表的foreach循环填充内容。在一种情况下,我希望能够将一个新选项添加到该列表中,然后选择该新选项。我可以将新值添加到列表中,并且可以为绑定的属性分配它的新值。我在输出中有注释,显示变量是应该的。

但是,在绑定属性尝试触发更改事件之前,UI不会更新,导致选择不选择新值,而是选择列表的第一个值。

我尝试在更新列表后立即调用stateHasChanged((,但这似乎没有改变任何事情。特定场景逻辑发生在通过单击按钮触发的异步任务中。

更新列表的逻辑:

async Task SaveProfile(){
Profiles.Insert(Profiles.Count - 1, new TableConfiguration() { ConfigurationId = NewProfile });
StateHasChanged();
ProfileDecode = NewProfile;
}

选择UI逻辑:

<select @bind=ProfileDecode class="form-control-sm">
@foreach (var prof in Profiles)
{
<option>@prof.ConfigurationId</option>
}
</select>

ProfileCode属性

private string ProfileDecode
{
get { return SelectedProfile.ConfigurationId; }
set
{
Console.WriteLine("passed value:" + value + " current value:" + ProfileDecode);
if (SelectedProfile.ConfigurationId != value)
{

SelectedProfile = Profiles.Single(p => p.ConfigurationId == value);
}
}
}

我很难根据您提供的代码片段构建一个工作模型。其他人可能会发现:如果他们这样做了,我会很乐意删除这个答案。

所以,我构建了一个我认为是你试图作为一个Razor页面实现的基本复制品。

这是有效的。如果这不能正确地模仿你所拥有的,请修改它,这样我们就可以帮助找出问题的根源。

@page "/"
<PageTitle>Index</PageTitle>
<select @bind="selectedItem" class="form-select">
@foreach (var country in Countries)
{
if (country == selectedItem) selectCountry = true;
else selectCountry = false;

<option @key= "country" selected="@selectCountry" value=country>@country</option>
}
</select>

<div class="m-2">
<div class="row">
<div class="col-6">
<input class="form-control form-text" type="text" @bind-value=this.newCountry />
</div>
<div class="col-6">
<button class="btn btn-dark" @onclick=this.AddToList>Add To List</button>
</div>
</div>
</div>
@code {
private string selectedItem = string.Empty;
private string newCountry = string.Empty;
private bool selectCountry = false;

private List<string> Countries = new List<string> { "UK", "France", "Spain" };
private async Task AddToList()
{
// mimic some async action such as a Db or api get
await Task.Delay(100);
if (!string.IsNullOrWhiteSpace(this.newCountry))
{
//Countries.Add(newCountry);
Countries.Insert(Countries.Count - 1, newCountry);
selectedItem = newCountry;
}
}
}

最新更新