Search code examples
asp.net-mvcrazormvc-editor-templates

In ASP.NET MVC, is there a way to get the loop index when using EditorTemplates?


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?


Solution

  • Phil Haack wrote up a nice blog post:

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