Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
708 views
in Technique[技术] by (71.8m points)

asp.net mvc - Getting index value on razor foreach

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
 @{int i = 0;}
 @foreach(var myItem in Model.Members)
 {
     <span>@i</span>
     @{i++;
      }
 }

// Use @{i++ to increment value}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...