You need to enable JavaScript to run this app. Blazor开发中如何在循环渲染客户列表时实现点击跳转详情页?
优惠活动
大模型
产品
解决方案
定价
更多

Blazor开发中如何在循环渲染客户列表时实现点击跳转详情页?

核心问题及修正方案

存在的错误点:

  • 闭包陷阱:Blazor的for循环中直接使用循环变量i绑定事件,所有点击事件触发时都会取到循环结束后的最终i值,无法对应每个条目对应的索引
  • 事件绑定逻辑错误:@onclick="NavToCustomer(i)"的写法会在页面渲染阶段直接执行方法,并非点击时触发
  • 取值错误:循环内没有按索引从customers数组取对应客户数据,直接用customer变量无法渲染正确内容
  • 循环范围错误:i < customers.Length-1的判定条件会漏掉数组最后一个客户条目

修正后代码

页面渲染部分
@for(int i = 0; i < customers.Length; i++)
{
    // 声明局部变量捕获当前循环的索引,解决闭包问题
    var currentIdx = i;
    var currentCustomer = customers[currentIdx];
    <tr>
        <td>@currentCustomer.Id</td>
        <td>@currentCustomer.CustomerId</td>
        <td>@currentCustomer.LastName</td>
        <td>@currentCustomer.FirstName</td>
        <td>@currentCustomer.Name1056Form</td>
        <td>@currentCustomer.TrapezeClientId</td>
        <td>@currentCustomer.CustomerNote</td>
        <td @onclick="() => NavToCustomer(currentIdx)"> Details</td>
    </tr>
}
跳转方法部分
private void NavToCustomer(int idx)
{
    // 注意:若详情页路由需要的是客户业务ID而非数组索引,替换为 customers[idx].Id 即可
    navigation.NavigateTo("/Customer/" + idx);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 12:06:08