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?
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.
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.
IndexOf seems to be useful here.
...
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
More info on my blog post http://jimfrenette.com/2012/11/razor-foreach-loop-with-index/
Or you could simply do this:
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:
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:
Move the switch statement to your view model builder and populate the CSS class there.
Take a look at this solution using Linq. His example is similar in that he needed different markup for every 3rd item.