You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MudBlazor Autocomplete输入新搜索值后列表不更新问题

问题分析与解决方案

你的问题根源在于全局的MovieList会累积所有历史搜索结果:每次调用Search方法时,你都往同一个列表里添加新数据,而不是返回当前搜索的独立结果。比如第一次搜fi得到一批电影,第二次搜fight club时,新结果会被追加到旧列表中,导致组件显示的是包含旧数据的混合列表,而非当前搜索的精准结果。

修复后的代码

Razor部分(无需修改)

<MudPaper>
    <MudAutocomplete T="string" Label="Search" @bind-Value="SearchValue" SearchFunc="@Search" ResetValueOnEmptyText="true"/>
</MudPaper>

C#代码部分

@code {
    private string SearchValue = string.Empty;

    private async Task<IEnumerable<string>> Search(string value)
    {
        var movies = await _msService.GetMultiSearch(value);
        if(movies is not null && movies.Results is not null)
        {
            // 每次搜索创建新列表,避免累积旧数据
            var currentMovieList = new List<string>();
            foreach(var movie in movies.Results)
            {
                if (!string.IsNullOrEmpty(movie.Name))
                {
                    currentMovieList.Add(movie.Name);
                }
                else if (!string.IsNullOrEmpty(movie.Title))
                {
                    currentMovieList.Add(movie.Title);        
                }
            }
            return currentMovieList;
        }
        else
        {
            // 返回空集合而非null,避免组件出现异常
            return Enumerable.Empty<string>();
        }
    }
}

可选优化(用LINQ简化代码)

如果想让代码更简洁,可以用LINQ替代foreach循环:

private async Task<IEnumerable<string>> Search(string value)
{
    var movies = await _msService.GetMultiSearch(value);
    return movies?.Results?.Select(m => 
        !string.IsNullOrEmpty(m.Name) ? m.Name : m.Title
    ).Where(name => !string.IsNullOrEmpty(name)) ?? Enumerable.Empty<string>();
}

内容的提问来源于stack exchange,提问作者spacemonki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 01:01:18