Razor - using foreach, insert html every nth element

I have displayed a large list of elements on my page using Razor and MVC 5. Here I have:

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

What I'm trying to do is what this outputs:

 <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 elements in a div tag. How can I do this in Razor?

+6
source share
3 answers

Not sure if you want to increase the number of Item (or if @item.Name really contains an incremented number), but the following code will increase both the class name (new div every 4th iteration) and the position 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> 
+8
source

foreach does not give you an index. It with#.

I suggest you change it to for .

 @foreach (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 *@ } 

You may be using Length instead of Count . If Model.Items is just IEnumerable not an array or List<> , you can call Model.Items.ToList() , etc. You will probably get this idea.

0
source

Here is my solution. Keep in mind that I have not 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 added Value to Linq Select if you need information inside the loop.

0
source

Source: https://habr.com/ru/post/1237150/


All Articles