In ASP.NET MVC, is there a way to get the loop ind

2019-05-24 10:03发布

问题:

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?

回答1:

Phil Haack wrote up a nice blog post:

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



回答2:

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/