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

Blazor WebAssembly根据用户输入ID调用GetFromJsonAsync获取数据

修复后的牙医预约查询实现

核心问题修正点

  • 给EditForm绑定提交事件,点击按钮触发数据获取逻辑
  • 修正dentistId的变量声明语法错误
  • 修复API请求中的变量名错误,移除多余的GetFromJsonAsync参数
  • 调整初始数据状态,让空状态提示正确显示
  • 添加加载状态,优化用户操作体验

完整代码

@page "/dentistappointments"
@using WhiteDentalClinic.Application.Models.AppointmentModel;
@using WhiteDentalClinic.Application.Models;
@inject HttpClient Http

<h3>DentistAppointments</h3>

<EditForm class="d-flex flex-column align-items-center" OnValidSubmit="LoadDentistAppointments">
    <InputText @bind-Value="@dentistId" class="mb-2" placeholder="输入牙医ID"/>

    <button type="submit" class="btn btn-primary" disabled="@isLoading">
        @(isLoading ? "加载中..." : "查看预约")
    </button>
</EditForm>

@if (isLoading)
{
    <p><em>正在加载预约数据...</em></p>
}
else if (appByDentist == null || !appByDentist.Any())
{
    <p><em>未找到该牙医的预约记录。</em></p>
}
else
{
    <table class="table mt-3">
        <thead>
            <tr>
                <th>ID</th>
                <th>预约时间</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var app in appByDentist)
            {
                <tr>
                    <td>@app.Id</td>
                    <td>@app.dateTime</td>
                </tr>
            }
        </tbody>
    </table>
}

@code {
    private List<AppointmentResponse> appByDentist;
    private string dentistId = "87459b92-79d6-44b3-850e-727d90519ba3";
    private bool isLoading;

    private async Task LoadDentistAppointments()
    {
        isLoading = true;
        try
        {
            var apiResult = await Http.GetFromJsonAsync<ApiResult<IEnumerable<AppointmentResponse>>>($"/api/Appointment/allapp/dentist{dentistId}");
            appByDentist = apiResult?.Result?.ToList() ?? new List<AppointmentResponse>();
        }
        catch (Exception ex)
        {
            // 可在此添加错误提示逻辑,比如弹窗显示请求失败
            appByDentist = new List<AppointmentResponse>();
        }
        finally
        {
            isLoading = false;
        }
    }

    // 若需初始化时加载默认ID的预约数据,取消下方注释
    // protected override async Task OnInitializedAsync()
    // {
    //     await LoadDentistAppointments();
    // }
}

关键修改说明

  1. 提交事件绑定:EditForm添加OnValidSubmit="LoadDentistAppointments",点击按钮时触发自定义数据加载方法
  2. 变量声明修正:将private var dentistId改为private string dentistId,符合C#语法规范
  3. API请求修正:移除GetFromJsonAsync的多余参数,确保URI使用正确的变量dentistId拼接
  4. 状态判断优化:初始将appByDentist设为null,结合!appByDentist.Any()判断空数据,正确显示提示文本
  5. 加载状态处理:添加isLoading变量,控制按钮禁用状态和加载提示,避免重复请求
  6. 异常处理:通过try-catch-finally块处理API请求失败场景,保证界面状态正常恢复

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 21:43:28