我正在尝试在表格中输出玩家的状态。并非所有玩家都会有一天的统计数据。我尝试了其他方法,但所有人仍在提示。这是我现在拥有的代码:

      <tbody>
            @foreach(var player in @ViewBag.Roster){
                int index = 0;
                <tr>
                    <td>@player.Name, @player.TeamName @player.Position</td>
                    if(@ViewBag.Stats[index] == null){
                        <td>--</td>
                        <td>--</td>
                        <td>--</td>
                        <td>--</td>
                    }
                    else{
                        <td>@ViewBag.Stats[index].Points</td>
                        <td>@ViewBag.Stats[index].Rebounds</td>
                        <td>@ViewBag.Stats[index].Assists</td>
                        <td>@ViewBag.Stats[index].Turnovers</td>
                    }
                </tr>
                index++;
            }

        </tbody>

异常详细信息:Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:无法对空引用执行运行时绑定(bind)

源错误:

第32行:}

第33行:else {

第34行:@ ViewBag.Stats [index] .Points

第35行:@ ViewBag.Stats [index]。反弹

第36行:@ ViewBag.Stats [index] .Assists

最佳答案

好吧,我在这里发布完整答案-

  • @之前尝试if(@ViewBag.Stats[index] == null){,然后从@内的@ViewBag中删除if,使其看起来像这样-@if(ViewBag.Stats[index] == null){
  • 您将在index = 0内设置foreach,因此将在每个循环中对其进行初始化。像这样在foreach外部初始化
    var index = 0;foreach ...

  • 如果您遇到示波器问题,请尝试以下操作-
    @{
        var index = 0;
        foreach (....) {
            .......
            index++
        }
    }
    

    10-05 20:46
    查看更多