I\'m iterating a List
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 hav
Or you could simply do this:
@foreach(var myItem in Model.Members)
{
<span>@Model.Members.IndexOf(myItem)</span>
}
@{int i = 0;}
@foreach(var myItem in Model.Members)
{
<span>@i</span>
@{i++;
}
}
// Use @{i++ to increment value}
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.
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:
<div class="@Model.GridCSS">
Move the switch statement to your view model builder and populate the CSS class there.
IndexOf seems to be useful here.
@foreach (myItemClass ts in Model.ItemList.Where(x => x.Type == "something"))
{
int currentIndex = Model.ItemList.IndexOf(ts);
@Html.HiddenFor(x=>Model.ItemList[currentIndex].Type)
...
Very Simple:
@{
int i = 0;
foreach (var item in Model)
{
<tr>
<td>@(i = i + 1)</td>`
</tr>
}
}`
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.
http://www.quirksmode.org/css/firstchild.html