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

.NET Core 7 Blazor下拉框显示为空问题排查与解决

问题原因与解决方案

核心原因

你的RefreshDropDownList()方法存在致命逻辑错误:在通过接口获取并反序列化得到4条ServerType数据后,立刻执行了ServerType = Array.Empty<ServerTypesClass>();,直接将刚拿到的有效数据清空,导致下拉框没有数据可遍历渲染。

另外还有两个次要问题:

  • AddClick()使用了async void,Blazor中异步方法推荐返回async Task,否则可能引发UI状态更新异常。
  • 绑定字段server_Type是string类型,但下拉框option的value绑定的是int类型的serverTypeId,类型不匹配可能导致后续选择值绑定失败。

解决步骤

1. 修复RefreshDropDownList方法

移除清空数组的多余代码,修改后代码如下:

private async Task RefreshDropDownList()
{
    var request = new HttpRequestMessage(HttpMethod.Get, config["API_URL"] + "ServerTypes");
    var client = ClientFactory.CreateClient();
    var response = await client.SendAsync(request);
    using var responsestream = await response.Content.ReadAsStreamAsync();
    // 移除清空数据的错误代码
    ServerType = await JsonSerializer.DeserializeAsync<IEnumerable<ServerTypesClass>>(responsestream);
    
    // 可选:若UI未自动更新,手动触发状态变更
    // StateHasChanged();
}

2. 修改AddClick方法返回类型

将async void改为async Task:

private async Task AddClick()
{
    await RefreshDropDownList();
}

3. 修正绑定字段类型

将ServerNamesClass中的server_Type类型改为int,与serverTypeId类型一致:

public class ServerNamesClass
{
    public int server_Type { get; set; }
}

验证效果

完成上述修改后重新运行项目,下拉框应该能正常展示4条ServerType数据,点击Add按钮也能正确刷新下拉列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 20:01:33