Reputation: 708
I have a div
and each div
has two divs
in it like this:
<div class="col">
<div class="item-c color1">..</div>
<div class="item-c color2">..</div>
</div>
I read data from database and I want to repeat this div with a foreach
statement.
I use below code but I get a Runtime Error
<div class="col">
@foreach (var item in Model)
{
<div class="item-c @("color" + index.ToString()) ">..</div>
if (index % 2 == 0)
{
<text></div><div class="col"></text>
}
index++;
if (index > 8) { index = 1; }
}
my result should like this : I am getting this Error :
Encountered end tag "div" with no matching start tag
Upvotes: 3
Views: 2529
Reputation: 1253
Bit late to the party but I found this approach works for me and is also readable:
@for (int i = 0; i < Model.SlotValues.Length; i++)
{
string key = Model.SlotValues[i].Key;
if (i % 2 == 0)
{
@:<div class="row">
}
<div class="col-md-6">
<label for="@key" class="form-selector__form__label form-selector__form__label--small text--light">@key</label>
@Html.TextBoxFor(x => x.SlotValues[i].Value, new { @class = "form-selector__form__input", placeholder = @key })
</div>
if (i % 2 == 1)
{
@:</div>
}
}
Upvotes: 0
Reputation:
Your code needs to be
@{ int index = 1; }
<div class="col">
@foreach(var item in Model.Items)
{
<div class="item-c color@(index)">..</div>
if (index % 2 == 0) // close the div and start a new one
{
@:</div><div class="col">
}
index++;
if (index > 8) { index = 1; }
}
</div>
Upvotes: 6
Reputation: 2415
Why not something like
@foreach (var item in Model)
{
<div class="col">
@foreach (var item2 in Model.Items.Select((model, index) => new { index, model }))
{
<div class="item-c [email protected]">
</div>
}
</div>
}
Upvotes: 0
Reputation: 1335
You can always use Html.Raw
in case if you need to close the tags inside the razor code. Checkout the below code which should work according to your requirement.
<div class="col">
@foreach (var item in Model)
{
<div class="item-c @("color" + index.ToString()) ">..</div>
if (index % 2 == 2)
{
@Html.Raw("</div> <div class="col">")
}
index++;
if (index > 8) { index = 1; }
}
</div>
Upvotes: 2
Reputation: 427
Your logic is incorrect, if the row count is odd, then you are not closing the last div, if your row count is even, your adding a open div and not closing it.
Removing the "if (index % 2 == 2)"
will produce the div as in your example
<div class="col">
<div class="item-c color1">..</div>
<div class="item-c color2">..</div>
</div>
<div class="col">
@foreach (var item in Model)
{
<div class="item-c @("color" + index.ToString())">..</div>
index++;
if (index > 8) { index = 1; }
}
</div>
Upvotes: 0