【问题标题】:Get a hold of the index in a for loop在 for 循环中获取索引
【发布时间】:2014-05-11 13:53:50
【问题描述】:

我让这个循环遍历专辑列表:

for (int i = 0; i < Model.Albums.Count; i++)
  {
 <div class="form-group">
  @Html.LabelFor(x => Model.Albums[i].AlbumCovers)
 </div>

如果[i],是否有可能获得保留?

[i] 是一个表示索引的 int,我想将它存储在 如果可能,变量?

谢谢!

【问题讨论】:

  • 为模型的每个元素存储它?
  • 是的,对于模型中的每个循环,我都想存储索引。这样做的原因是我想在 actionlik 中将索引作为参数传递。

标签: c# asp.net for-loop indexing


【解决方案1】:

您不必存储索引来为模式项创建链接。您可以做的是为模型的每次迭代生成一个操作链接。这是给您的示例:

for (int i = 0; i < Model.Albums.Count; i++)
  {
    @Html.ActionLink("Edit Record", "Edit", new {Id=i})
  }

这里Edit Record是链接的文本,Edit是控制器动作名称,Id是控制器编辑动作的参数。

【讨论】:

  • 这正是我想要的!
【解决方案2】:

不清楚你在问什么,i 已经是一个包含整数的变量,但如果你愿意,你可以这样做:

for (int i = 0; i < Model.Albums.Count; i++)
{
    int index = i;
    @Html.LabelFor(x => Model.Albums[i].AlbumCovers)
}

如果你想为专辑捕获一个变量,你可以这样做:

for (int i = 0; i < Model.Albums.Count; i++)
{
    Album album = Model.Albums[i];
    @Html.LabelFor(x => album.AlbumCovers)
}

【讨论】:

  • 这段代码也给出了我想要的结果。谢谢
猜你喜欢
  • 2017-08-13
  • 1970-01-01
  • 2012-08-20
  • 2013-03-19
  • 1970-01-01
  • 2013-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多