英文:
How to alternate a row color for a Bootstrap grid system
问题
我有一个循环在我的模型中,我只想使每个交替的Div行变成不同的颜色。有没有办法我可以检查我的变量i模2 == 0,然后设置背景颜色,或者有更好的方法
@for (var i = 0; i < Model.Transactions.Count; i++)
{
<div class="row">
<div class="col">
<label asp-for="@Model.Transactions[i].TransactionId" />@Model.Transactions[i].TransactionId
</div>
英文:
I have a loop on my MODEL in the view and I simply want to make every alternate Div ROW a different color. Is there a way I can check if my variable i Modulus by 2 ==0 and then set the backcolor, or is there even a better way
@for (var i = 0; i < Model.Transactions.Count; i++)
{
<div class="row">
<div class="col">
<label asp-for="@Model.Transactions[i].TransactionId" />@Model.Transactions[i].TransactionId
</div>
答案1
得分: 1
I don't have any code to translate in the provided text.
英文:
Your own answer uses the right modulus operator to check for an even/odd index value.
> I don't know if this the best way to do it but below is how I overcome my issue
Adding a class name instead enables more style flexibility. (The snippet below assumes you have a section called Styles
in your _Layout.cshtml
.)
@section Styles {
<style>
.odd-row {
background-color: #f1f1f1;
}
.even-row {
background-color: #e1e1e1;
}
</style>
}
@for (int i = 0; i < Model.Transactions.Count; i++)
{
string altClassName = i % 2 == 0 ? "even-row" : "odd-row";
<div class="row @altClassName">
<div class="col">
<label asp-for="@Model.Transactions[i].TransactionId">@Model.Transactions[i].TransactionId</label>
</div>
</div>
}
答案2
得分: 0
我不知道这是否是最佳方法,但以下是我克服问题的方式
<div class="row" style="@(i%2 == 0 ? "background-color:aliceblue" : "background-color:white")">
英文:
I don't know if this the best way to do it but below is how I overcome my issue
<div class="row" style="@(i%2 == 0 ? "background-color:aliceblue" : "background-color:white")">
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论