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

2019-05-24 09:39发布

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?

2条回答
Deceive 欺骗
2楼-- · 2019-05-24 10:22
狗以群分
3楼-- · 2019-05-24 10:30

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/

查看更多
登录 后发表回答