在Razor中增加一个索引计数器

时间:2018-04-27 15:16:58

标签: c# razor asp.net-core

我有一个View模型,它有一个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]值。

2 个答案:

答案 0 :(得分:1)

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

Sub sort_largest()

Dim i As Long

i = 1 + 1

Do Until Cells(1, i) = ""




Columns("A:A").Select
    ActiveWorkbook.Worksheets("Pivot Tables").Sort.SortFields.clear
    ActiveWorkbook.Worksheets("Pivot Tables").Sort.SortFields.Add Key:=Range("A1" _
        ), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Pivot Tables").Sort
    .SetRange Range("A:A")
    .Header = xlNo
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

i = i + 1
Loop

End Sub

否则你可以通过这个找到你的索引:

@{
    // 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++;
}
循环中的

。我还没有检查过语法(应该在哪里添加@),但你明白我的意思。

答案 1 :(得分:1)

使用for循环代替foreach。

@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>
}
相关问题