asp.net-mvc 在 razor foreach 上获取索引值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10326406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting index value on razor foreach
提问by lloydphillips
I'm iterating a List<T>in a razor foreach loop in my view which renders a partial. In the partial I'm rendering a single record for which I want to have 4 in a row in my view. I have a css class for the two end columns so need to determine in the partial whether the call is the 1st or the 4th record. What is the best way of identifying this in my partial to output the correct code?
我List<T>在一个 razor foreach 循环中迭代 a在我的视图中呈现部分。在部分中,我正在渲染一个记录,我希望在我的视图中连续显示 4 个记录。我有一个用于两端列的 css 类,因此需要在部分中确定调用是第 1 条记录还是第 4 条记录。在我的部分中识别这一点以输出正确代码的最佳方法是什么?
This is my main page which contains the loop:
这是我的主页,其中包含循环:
@foreach (var myItem in Model.Members){
//if i = 1
<div class="grid_20">
<!-- Start Row -->
//is there someway to get in for i = 1 to 4 and pass to partial?
@Html.Partial("nameOfPartial", Model)
//if i = 4 then output below and reset i to 1
<div class="clear"></div>
<!-- End Row -->
</div>
}
I figure I can create a int that I can update on each pass and render the text no problem here but it's passing the integer value into my partial I'm more concerned about. Unless there's a better way.
我想我可以创建一个 int ,我可以在每次传递时更新它并在此处渲染文本没有问题,但是它将整数值传递给我更关心的部分。除非有更好的办法。
Here is my partial:
这是我的部分:
@{
switch()
case 1:
<text>
<div class="grid_4 alpha">
</text>
break;
case 4:
<text>
<div class="grid_4 omega">
</text>
break;
default:
<text>
<div class="grid_4">
</text>
break;
}
<img src="Content/960-grid/spacer.gif" style="width:130px; height:160px; background-color:#fff; border:10px solid #d3d3d3;" />
<p><a href="member-card.html">@Model.Name</a><br/>
@Model.Job<br/>
@Model.Location</p>
</div>
Not sure if I'm having a blonde day today and this is frightfully easy but I just can't think of the best way to pass the int value in. Hope someone can help.
不确定我今天是否有一个金发碧眼的日子,这非常容易,但我想不出传递 int 值的最佳方法。希望有人能提供帮助。
回答by noamtcohen
@{int i = 0;}
@foreach(var myItem in Model.Members)
{
<span>@i</span>
@{i++;
}
}
// Use @{i++ to increment value}
// 使用@{i++ 来增加值}
回答by Jim Frenette
//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 my blog post http://jimfrenette.com/2012/11/razor-foreach-loop-with-index/
有关我的博客文章的更多信息 http://jimfrenette.com/2012/11/razor-foreach-loop-with-index/
回答by brightgarden
Take a look at this solution using Linq.His example is similar in that he needed different markup for every 3rd item.
使用 Linq查看此解决方案。他的例子很相似,因为他需要为每第三个项目进行不同的标记。
foreach( var myItem in Model.Members.Select(x,i) => new {Member = x, Index = i){
...
}
回答by Manoj De Mel
Or you could simply do this:
或者你可以简单地这样做:
@foreach(var myItem in Model.Members)
{
<span>@Model.Members.IndexOf(myItem)</span>
}
回答by Timothy Strimple
Is there a reason you're not using CSS selectors to style the first and last elements instead of trying to attach a custom class to them? Instead of styling based on alpha or omega, use first-child and last-child.
您是否有理由不使用 CSS 选择器来设置第一个和最后一个元素的样式,而不是尝试将自定义类附加到它们?不要使用基于 alpha 或 omega 的样式,而是使用 first-child 和 last-child。
回答by user2464265
IndexOf seems to be useful here.
IndexOf 在这里似乎很有用。
@foreach (myItemClass ts in Model.ItemList.Where(x => x.Type == "something"))
{
int currentIndex = Model.ItemList.IndexOf(ts);
@Html.HiddenFor(x=>Model.ItemList[currentIndex].Type)
...
...
回答by peeyush singh
Very Simple:
很简单:
@{
int i = 0;
foreach (var item in Model)
{
<tr>
<td>@(i = i + 1)</td>`
</tr>
}
}`
回答by Louise Eggleton
All of the above answers require logic in the view. Views should be dumb and contain as little logic as possible. Why not create properties in your view model that correspond to position in the list eg:
以上所有答案都需要视图中的逻辑。视图应该是愚蠢的并且包含尽可能少的逻辑。为什么不在您的视图模型中创建与列表中的位置相对应的属性,例如:
public int Position {get; set}
In your view model builder you set the position 1 through 4.
在您的视图模型构建器中,您将位置设置为 1 到 4。
BUT .. there is even a cleaner way. Why not make the CSS class a property of your view model? So instead of the switch statement in your partial, you would just do this:
但是 .. 甚至还有一种更清洁的方法。为什么不让 CSS 类成为视图模型的属性?因此,您只需执行以下操作,而不是部分中的 switch 语句:
<div class="@Model.GridCSS">
Move the switch statement to your view model builder and populate the CSS class there.
将 switch 语句移动到您的视图模型构建器并在那里填充 CSS 类。
回答by Just Fair
In case you want to count the references from your model( ie: Client has Address as reference so you wanna count how many address would exists for a client) in a foreach loop at your view such as:
如果您想在您的视图中的 foreach 循环中计算来自模型的引用(即:客户端将地址作为引用,因此您想计算客户端存在多少地址),例如:
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.DtCadastro)
</td>
<td style="width:50%">
@Html.DisplayFor(modelItem => item.DsLembrete)
</td>
<td>
@Html.DisplayFor(modelItem => item.DtLembrete)
</td>
<td>
@{
var contador = item.LembreteEnvolvido.Where(w => w.IdLembrete == item.IdLembrete).Count();
}
<button class="btn-link associado" data-id="@item.IdLembrete" data-path="/LembreteEnvolvido/Index/@item.IdLembrete"><i class="fas fa-search"></i> @contador</button>
<button class="btn-link associar" data-id="@item.IdLembrete" data-path="/LembreteEnvolvido/Create/@item.IdLembrete"><i class="fas fa-plus"></i></button>
</td>
<td class="text-right">
<button class="btn-link delete" data-id="@item.IdLembrete" data-path="/Lembretes/Delete/@item.IdLembrete">Excluir</button>
</td>
</tr>
}
do as coded:
按编码做:
@{ var contador = item.LembreteEnvolvido.Where(w => w.IdLembrete == item.IdLembrete).Count();}
and use it like this:
并像这样使用它:
<button class="btn-link associado" data-id="@item.IdLembrete" data-path="/LembreteEnvolvido/Index/@item.IdLembrete"><i class="fas fa-search"></i> @contador</button>
ps: don't forget to add INCLUDE to that reference at you DbContext inside, for example, your Index action controller, in case this is an IEnumerable model.
ps:不要忘记将 INCLUDE 添加到您 DbContext 内部的引用中,例如,您的 Index 操作控制器,以防这是一个 IEnumerable 模型。
回答by ppolyzos
You could also use deconstruction and tuples and try something like this:
您还可以使用解构和元组并尝试以下操作:
@foreach (var (index, member) in @Model.Members.Select((member, i) => (i, member)))
{
<div>@index - @member.anyProperty</div>
if(index > 0 && index % 4 == 0) { // display clear div every 4 elements
@: <div class="clear"></div>
}
}
For more info you can have a look at this link
有关更多信息,您可以查看此链接

