blazor WASM new select 选项刷新速度比分配新绑定值慢

blazor WASM new select options refresh slower than assignment of new bind value

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

但是 UI 在绑定 属性 尝试触发导致 select 不是 select 新值但相反,列表的第一个值是什么。

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

更新列表的逻辑:

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

Select UI 逻辑:

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

ProfileDecode 属性

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