4

I am having an issue with my foreach loop:

@for(int i = 0; i < Model.Count(); i += 3)
{
    <div class="row">
        @foreach (var item in Model) 
        {
            <div class="col-md-4 portfolio-item">
                <a href="@Html.DisplayFor(modelItem => item.UrlSlug)">
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">
                </a>
                <h3>
                <a href="@Html.DisplayFor(modelItem => item.UrlSlug)">@Html.DisplayFor(modelItem => item.Title)</a>
                </h3>
                <p>@Html.DisplayFor(modelItem => item.ShortDescription)</p>
                @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
                @Html.ActionLink("Details", "Details", new { id = item.Id }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.Id })
            </div>
        }
    </div>
}

This method displays one big long list, however I only want to display three (3x) <div class="col-md-4 portfolio-item"> inside <div class="row"> after three portfolio items has been populated I then want to create another <div class="row"> and populate the next three <div class="col-md-4 portfolio-item">.

How can I achieve this?

1 Answer 1

9

You could use an outer for loop like for (int i = 0; i < Model.Count; i += 3) than the <div class="row"> and your actual foreach uses Model.Skip(i).Take(3).

@for(int i = 0; i < Model.Count(); i += 3)
{
    <div class="row">
        @foreach (var item in Model.Skip(i).Take(3)) 
        {
            <div class="col-md-4 portfolio-item">
                <a href="@Html.DisplayFor(modelItem => item.UrlSlug)">
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">
                </a>
                <h3>
                <a href="@Html.DisplayFor(modelItem => item.UrlSlug)">@Html.DisplayFor(modelItem => item.Title)</a>
                </h3>
                <p>@Html.DisplayFor(modelItem => item.ShortDescription)</p>
                @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
                @Html.ActionLink("Details", "Details", new { id = item.Id }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.Id })
            </div>
        }
    </div>
}
Sign up to request clarification or add additional context in comments.

3 Comments

@GarrithGraham What is the type of Model?
I forgot the @ in the first line and amended .Count to .Count() as IEnumerable does not have that property. You will also need to import LINQ with @using System.Linq at the top of your view.
Damn it, I wanted to declare i before and then realized that I only forgot the @. It should work now!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.