在 Razor 中递增索引计数器

Increment an Index Counter in Razor

提问人:coolhand 提问时间:4/27/2018 更新时间:8/11/2021 访问量:9411

问:

我有一个视图模型,它有一个对象,我循环访问该对象以显示数据表。该模型还具有一个值数组,我想在同一表中显示这些值。IEnumerable

可枚举数据以循环方式显示。我尝试添加一个索引计数器来遍历同一表上的数组,但计数器永远不会递增。如何将这两个元素组合到同一个表格中?foreach

        //my foreach loop goes through my Item List
        @foreach (var item in @Model.ItemList)
        {
            //i need an indexer to go through MyArray
            var i = 0;
            <tr>
                <td>@Html.DisplayFor(shortDate => item.StartDate)</td><td>@Html.DisplayFor(shortDate => item.EndDate)</td><td>@Model.MyArray[i]</td><td>@item.Value</td>
            </tr>
            //here the index 'i' never seems to increment
            i++;
        }

结果是只显示所有行的值。MyArray[0]

C# Razor ASP.NET-Core

评论


答:

8赞 Anastasios Selmani 4/27/2018 #1

每次代码进入循环时,您的“i”都会设置为零。您必须在循环之外初始化计数器,如下所示:

@{
    // Here the initialization happens outside of the loop
    var i = 0;
} 

@foreach (var item in @Model.ItemList)
{      
    <tr>
        <td>@Html.DisplayFor(shortDate => item.StartDate)</td><td>@Html.DisplayFor(shortDate => item.EndDate)</td><td>@Model.MyArray[i]</td><td>@item.Value</td>
    </tr>
    //here your index should increment correctly
    i++;
}

否则,你可以通过以下方式找到你的索引:

int index = @Model.ItemList.IndexOf(item);
<tr>
    ...
    <td>
      @index
    </td>
    ...
</tr>

在你的循环中。

评论

0赞 coolhand 4/27/2018
在这种情况下,如何初始化索引器。当我使用您建议的代码时,我收到一个错误。我也试过了,我也遇到了一个错误@var i = 0
0赞 coolhand 4/27/2018
谢谢你,使用这个技巧Model.ItemList.IndexOf(item)
0赞 Anastasios Selmani 4/27/2018
@coolhand 我还在我的答案中添加了初始化所需的 Razor 语法
2赞 user1023602 4/27/2018 #2

使用循环而不是 foreach。for

@for (int i = 0; i < Model.ItemList.Count(); i++)
{
    var item = Model.ItemList[i];
    <tr>
        <td>@Html.DisplayFor(shortDate => item.StartDate)</td><td>@Html.DisplayFor(shortDate => item.EndDate)</td><td>@Model.MyArray[i]</td><td>@item.Value</td>
    </tr>
}