2

In ASP.NET MVC, is there a way to get the loop index when using EditorTemplates? In the past, when I need to know the index of an element in the model, I forgo using EditorTemplates in favor of a for loop in the base view. I am wondering if there is a way to get the index of an element while still using EditorTemplates.

My for loop example:

        @{int contentIndex = 0;}
        @foreach (var item in Model.Content)
        {
            <p id="content@(contentIndex)">
                @Html.TextArea("Content["+contentIndex+"]", item)
            </p>
            contentIndex++;
        }

See how I use the contentIndex for the paragraph id? I want to be able to do that using an EditorTemplate instead of a for loop. Is this possible?

Ryand.Johnson
  • 1,906
  • 2
  • 16
  • 22
quakkels
  • 11,676
  • 24
  • 92
  • 149

2 Answers2

2

Phil Haack wrote up a nice blog post:

http://haacked.com/archive/2011/04/14/a-better-razor-foreach-loop.aspx

Leniency
  • 4,984
  • 28
  • 36
Phil Klein
  • 7,344
  • 3
  • 30
  • 33
0

This worked for me, got it from Getting index value on razor foreach

//this gets you both the item (myItem.value) and its index (myItem.i)
@foreach (var myItem in Model.Members.Select((value,i) => new {i, value}))
{
    <li>The index is @myItem.i and a value is @myItem.value.Name</li>
}

More info on this blog post http://jimfrenette.com/2012/11/razor-foreach-loop-with-index/

Community
  • 1
  • 1
Zymotik
  • 6,412
  • 3
  • 39
  • 48