Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically add boostrap rows and columns in mvc

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?

like image 954
G Gr Avatar asked Jan 09 '23 13:01

G Gr


1 Answers

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>
}
like image 98
Franky Avatar answered Jan 16 '23 12:01

Franky