【问题标题】:In ASP.NET MVC, is there a way to get the loop index when using EditorTemplates?在 ASP.NET MVC 中,有没有办法在使用 EditorTemplates 时获取循环索引?
【发布时间】:2011-12-29 15:27:23
【问题描述】:

在 ASP.NET MVC 中,有没有办法在使用 EditorTemplates 时获取循环索引?过去,当我需要知道模型中元素的索引时,我会放弃使用 EditorTemplates,而是在基本视图中使用 for 循环。我想知道是否有办法在仍然使用 EditorTemplates 的同时获取元素的索引。

我的 for 循环示例:

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

看看我如何使用contentIndex 作为段落ID?我希望能够使用 EditorTemplate 而不是 for 循环来做到这一点。这可能吗?

【问题讨论】:

    标签: asp.net-mvc razor mvc-editor-templates


    【解决方案1】:

    【讨论】:

      【解决方案2】:

      这对我有用,从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>
      }
      

      关于这篇博文的更多信息http://jimfrenette.com/2012/11/razor-foreach-loop-with-index/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-25
        • 2011-11-26
        • 2018-09-02
        • 2022-07-08
        • 2018-08-10
        • 2020-11-18
        • 1970-01-01
        • 2011-04-30
        相关资源
        最近更新 更多