Reputation: 2986
I am working on a personal MVC project using ASP.Net MVC where I have the following code:
<div class="container">
@foreach(var item in @Model)
{
<div class="row">
<div class="col-md-4">
//TODO... Render html here
</div>
</div>
}
</div>
What I am trying to achieve is to render the row class after every 3th iteration. So, the idea is to have something like this:
<div class="row">
<div class="col-md-4">HTML HERE</div>
<div class="col-md-4">HTML HERE</div>
<div class="col-md-4">HTML HERE</div>
</div>
<div class="row"> -->render this if the after the 3th iteration in the foreach
<div class="col-md-4">HTML HERE</div>
<div class="col-md-4">HTML HERE</div>
<div class="col-md-4">HTML HERE</div>
</div>
I was trying to create a variable in razor @{int i=0;} and use it in a if statement like this:
@if(i%3 == 0){
//render the row class
<div class="row">
}
But, I am getting some compile errors.
Has anyone do something similar? Or do you know if it's possible to do that in ASP.Net MVC using Razor?
Regards!
Upvotes: 0
Views: 1742
Reputation: 24
Two options
If entire block of and its children are to be rendered at regular intervals
@{
int index = 0;
}
@foreach (var item in @Model)
{
if(index % 3 == 0)
{
<div class="row">
<div class="col-md-4">
@* //TODO... Render html here*@
</div>
</div>
}
index++;
}
If the children are to be rendered every time but only the has to be rendered at regular intervals
@{
int index = 0;
}
@foreach (var item in @Model)
{
if (index % 3 == 0)
{
@: <div class="row">
}
<div class="col-md-4">
@* //TODO... Render html here*@
</div>
if (index % 3 == 0)
{
@: </div>
}
index++;
}
Upvotes: 1
Reputation: 218832
You can loop through the collection and render it. Keep a counter to check the column count and use that in the loop to determine whether a new row should start.
<div>
@{
var numberOfColsNeeded = 3;
var totalCounter = Model.Count();
var itemCounter = 1;
}
@foreach (var item in Model)
{
if (itemCounter % numberOfColsNeeded == 1)
{
@:<div class="row">
}
<div class="col-md-4">
<span>Some html</span>
<span> @item.Name</span>
</div>
if ((itemCounter % numberOfColsNeeded == 0) || ((itemCounter) == totalCounter))
{
@:</div>
}
itemCounter++;
}
</div>
Upvotes: 0