在ASP。NET MVC,是否有一种方法可以在使用编辑器模板时获取循环索引?

时间:2022-12-11 23:30:43

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.

在ASP。NET MVC,是否有一种方法可以在使用编辑器模板时获取循环索引?过去,当我需要知道模型中元素的索引时,我放弃使用EditorTemplates,而在基本视图中使用for循环。我想知道是否有一种方法可以在使用editortemplate时获取元素的索引。

My for loop example:

我的for循环的例子:

        @{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?

看到我如何为段落id使用contentIndex了吗?我希望能够使用编辑器模板而不是for循环来实现这一点。这是可能的吗?

2 个解决方案

#1


2  

Phil Haack wrote up a nice blog post:

菲尔·哈克写了一篇不错的博客:

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

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

#2


0  

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

这对我很有效,从razor的指数价值中得来的

//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/

更多信息请访问这篇博客http://jimfrenette.com/2012/11/razor-foreach-loop-with-index/

#1


2  

Phil Haack wrote up a nice blog post:

菲尔·哈克写了一篇不错的博客:

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

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

#2


0  

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

这对我很有效,从razor的指数价值中得来的

//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/

更多信息请访问这篇博客http://jimfrenette.com/2012/11/razor-foreach-loop-with-index/