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

Blazor技术问题:为何无法在City.razor中导入城市值?

解决Blazor中City.razor编辑页面无法获取城市数据的问题

问题核心:你在City.razor中初始化的city是一个全新的空对象,没有根据路由传入的CityId从CityService里获取对应的城市数据,所以编辑分支无法显示正确的城市名称等信息。

修复步骤:

  • 当CityId存在时,在组件生命周期中调用服务获取对应城市数据
  • 可选:添加加载状态提示,避免数据未加载时出现空值显示

修改后的City.razor代码:

@page "/city"
@page "/city/{CityId}"
@inject ICityService CityService
@inject NavigationManager NavigationManager

@if (isLoading)
{
    <p>加载中...</p>
}
else if (CityId == null)
{
    <PageTitle>Add a new City</PageTitle>
    <h3>Add a new City</h3>
    <!-- 这里可添加新增城市的表单 -->
}
else
{
    <PageTitle>Edit @city.CityName</PageTitle>
    <h3>Edit @city.CityName</h3>
    <!-- 这里可添加编辑城市的表单,绑定city的属性 -->
}

@code
{
    [Parameter]
    public int? CityId { get; set; }

    private City city = new City { Country = new Country() };
    private bool isLoading;

    protected override async Task OnParametersSetAsync()
    {
        // 当CityId有值且和当前city的Id不符时,重新获取数据
        if (CityId.HasValue && city.CityId != CityId.Value)
        {
            isLoading = true;
            // 从服务中获取对应Id的城市数据
            city = await CityService.GetCityById(CityId.Value);
            // 处理未找到城市的情况
            if (city == null)
            {
                NavigationManager.NavigateTo("/cities");
                return;
            }
            isLoading = false;
        }
    }
}

关键说明:

  1. 使用OnParametersSetAsync:相比OnInitializedAsync,这个方法会在组件参数(比如路由中的CityId)变化时触发,更适配编辑场景下的参数更新需求。
  2. 数据加载逻辑:通过CityId从服务获取指定城市,需确保你的ICityService已实现GetCityById(int id)方法,示例实现参考:
public async Task<City> GetCityById(int id)
{
    var response = await _httpClient.GetFromJsonAsync<City>($"api/cities/{id}");
    return response;
}
  1. 错误处理:如果未找到对应城市,自动跳回城市列表页面,避免显示无效数据。
  2. 加载状态:添加isLoading变量,在数据加载时显示提示,提升用户体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 08:22:49