Steven
Steven

Reputation: 18859

Razor - using foreach, insert html every nth item

I'm outputting a large list of items on my page using Razor and MVC 5. Here's what I have currently:

@foreach (var item in Model.Items)
{
    <a>@item.Name</a>
}

What I'm trying to do is something that would output this:

<div class="tab-0">
    <a>Item 1</a>
    <a>Item 2</a>
    <a>Item 3</a>
    <a>Item 4</a>
</div>
<div class="tab-1">
    <a>Item 5</a>
    <a>Item 6</a>
    <a>Item 7</a>
    <a>Item 8</a>
</div>
<div class="tab-2">
    <a>Item 9</a>
    <a>Item 10</a>
    <a>Item 11/a>
    <a>Item 12</a>
</div>

I need to group every 4 items within a div tag. How can I do that in Razor?

Upvotes: 6

Views: 5346

Answers (3)

Meligy
Meligy

Reputation: 36594

foreach doesn't give you the index. That's C#.

I suggest you change it to for.

@for (var index = 0; index < Model.Items.Count(); index++)
{
    var item = Model.Items[index];
    <a>@item.Name</a>
    @* Use `item` or `index` as you wish here *@
}

Maybe you'll use Length instead of Count. If Model.Items is just IEnumerable not array or List<>, you might want to call Model.Items.ToList(), etc. You probably get the idea.

Upvotes: 0

Marko Jovanov
Marko Jovanov

Reputation: 418

Here's my take on the solution. Bear in mind that I haven't compiled the code myself, so please check it:

foreach(var item in Model.Items.Select((x, i) => new {Index = i, Value = x}))
{
    if (item.Index % 4 == 0)
    { 
        <div class="tab-@(item.Index/4)">  
    }

            <a>Item @(item.Index + 1)</a>

    if (item.Index % 4 == 0)
    { 
        </div>
    }
} 

// If the number of items has a remainder of 4, close the div tag
if(Model.Items.Count %4 != 0)
{
    @:</div>
}

I have added the Value in Linq Select in case you need the information inside the loop.

Upvotes: 0

user3559349
user3559349

Reputation:

Not sure if your wanting to increment the Item number (or if @item.Name actually contains the incremented number), but the following code will increment both the class name (a new div every 4th iteration) and the item number.

@{ var t = 0; var i = 1;  }
<div class="tab-@t">  
    @foreach (var item in Model.Items)
    {
        <a>Item @i</a> // this may be just @item.Name?
        if (i % 4 == 0)
        {
            t++;
            @:</div><div class="tab-"@t>
        }
        i++;
    }
</div>

Upvotes: 9

Related Questions