I'm trying to get some code to work to make rows from a List of Items. I had done it before but for some reason it's not properly adding the closing tags.
<code>
@if (Model != null)
{
var start = 0;
foreach (var item in Model)
{
if (start == 0)
{
@:<div ><div >
start ;
}
else if (Model.Count == start)
{
@:</div>
}
else if (start % 3 == 1 && start > 1)
{
@:</div>
start ;
}
else
{
var price = string.Format("{0:0.00}", item.MenuItemPrice);
<div >
<img src="~/SiteImages/MenuHome.png" style="width:128px" />
<div >
<div >
@item.MenuItemName
<hr />
</div>
<p >
@item.MenuItemDesc - @price
</p>
<button id="fpPlatter">View</button>
</div>
</div>
@:</div>
start ;
}
}
}
</code>
It does write the row but it won't close the col-lg-4. It should write a row, a col-lg-4, then add 3 items based on the modulus and close them at the end. I'm probably overlooking some thing as the List is added. Any input appreciated. I can add a screenshot.
CodePudding user response:
You are not handling all the items with the current logic. For example on the first iteration the opening div is created, but the item is not written. The html you have in the else probably needs to be done unconditionally and the rest of the optional html needs to be handled the body of the foreach loop in relation to the item html so that it lands in the proper place.
CodePudding user response:
Try this...
<code>
@if (Model != null)
{
var currentCard = 0;
foreach (var item in Model.Products)
{
currentCard ;
if (currentCard % 3 == 1)
{
@:<div >
}
<div >
<div >
@*
<div >
<img src="~/SiteImages/MenuHome.png" style="width:128px" />
</div>
*@
<div >
<div >
@item.MenuItemName
<hr />
</div>
<p >
@item.MenuItemDesc - @string.Format("{0:0.00}", item.MenuItemPrice)
</p>
<button id="fpPlatter">View</button>
</div>
</div>
</div>
if (currentCard % 3 == 0 || currentCard == Model.Products.Count)
{
@:</div>
}
}
}
</code>
You will need to change Model.Products to your required Model... it was just me playing around.
CodePudding user response:
There is an issue with your conditional logic. However, rather than correct it, you could just abandon it and use Bootstrap's grid system to layout your rows for you.
outside of your foreach loop, open a row div
inside your loop, output a card contained inside a div sized using the grid system
<div > <div > ... </div> </div>after exiting your loop, close the row div
This is the method recommended in Bootstrap's own documentation. It is simpler to implement and also requires less work server-side to generate your HTML.
