Reputation: 7818
Is there anyway to keep track of a Razor loop, and half way through it take some action, and then continue with the loop:
Eg. I have this:
@foreach (var item in Model)
{
@Html.DisplayFor(modelItem => item.Assignee)
}
I would like (pseudo):
@var halfway = Model.count / 2
@var count = 0
@foreach (var item in Model) until count == halfway
{
@Html.DisplayFor(modelItem => item.Assignee)
}
// hear we've reached halfway through, so I want to change add some HTML to the screen
<hr />
@foreach remainder (var item in Model)
{
@Html.DisplayFor(modelItem => item.Assignee)
}
Thanks for any advice,
Mak
Upvotes: 1
Views: 2131
Reputation: 371
A bit shorter option
@{
var halfway = Model.Count()/2;
var count = 0;
}
@foreach (var item in Model)
{
@Html.DisplayFor(modelItem => item.Assignee)
if (count++ == halfway)
{
<p>Your html code</p>
}
}
Upvotes: 1
Reputation: 12248
You could do it as a single loop and keep track of where you are, when you reach the halfway point you can display the additional html.
@{
var halfway = Model.Count() / 2;
var count = 0;
var isHalfway = false;
}
@foreach (var item in Model)
{
if ((count >= halfway) && (!isHalfway))
{
isHalfway = true;
<hr />
}
@Html.DisplayFor(modelItem => item.Assignee)
count++;
}
Another option would be to use Linq:
@foreach (var item in Model.Take(halfway))
{
@Html.DisplayFor(modelItem => item.VideoCode)
}
<hr />
@foreach (var item in Model.Skip(halfway))
{
@Html.DisplayFor(modelItem => item.VideoCode)
}
Upvotes: 1
Reputation: 6772
You can use LINQ on the list of your items:
@var halfway = Model.count / 2
@foreach (var item in Model.Take(halfway))
{
@Html.DisplayFor(modelItem => item.Assignee)
}
// Do your thing
<hr />
@foreach remainder (var item in Model.Skip(halfway))
{
@Html.DisplayFor(modelItem => item.Assignee)
}
Upvotes: 4
Reputation: 18759
@for(int i=0;i<= halfway ; i++)
{
@Html.DisplayFor(modelItem => item.Assignee)
}
Upvotes: 2
Reputation: 10400
I suggest you use a for
loop, not a foreach
loop, provided of course your Model supports it. Then you can use count as the iterator and just check whether the count == halfway
.
Upvotes: 1