Reputation: 3
can someone help me with this task
@foreach (var item in Model.Premium)
{
<div class="col-md-2">
<div id="test" class="panel">
<div class="panel-heading text-center">
<h1 class="panel-title" style="font-size:x-large;font-weight:400">
@item.year
</h1>
</div>
<div class="panel-body text-center" style="font-size:x-large;font-weight:300">
[email protected]
</div>
</div>
</div>
<script>
var year = @item.cy_year;
var OddOrEven = year % 2;
if (OddOrEven = 0) {
$('#test').addClass("panel-default");
}
else
{
$('#test').addClass("panel-info");
}
</script>
}
In this code I'm getting list of years and prices from a table. What I want is to add each year with it's price in bootstrap panel, then check if the panel is odd or even. For all of the odd panels, I want to add the bootstrap class "panel-default"
and for all of the even panels I want to add the bootstrap class "panel-info"
.
Thanks
Upvotes: 0
Views: 849
Reputation: 449
So a couple problems
Here is how you could do it in razor
@foreach (var item in Model.Premium)
{
var classForDiv = "panel-info";
if(item.cy_year % 2 == 0) {
classForDiv = "panel-default";
}
<div class="col-md-2">
<div id="test" class="panel @classForDiv"> // Need to change the id to be unique for each iteration
<div class="panel-heading text-center">
<h1 class="panel-title" style="font-size:x-large;font-weight:400">@item.year</h1></div>
<div class="panel-body text-center" style="font-size:x-large;font-weight:300"> [email protected]</div>
</div>
</div>
}
Upvotes: 0
Reputation: 16430
The problem is your jQuery, it's targetting an element with an ID 'test' but in each iteration you output the same ID, so jQuery can't detect which element you want to target. You don't actually need any javascript.
In your code you were calculating odd or even based on the item's year, you can actually just use a count on the iterator for that. If you do really want to use the Year, just replace
@Html.Raw(i % 2 == 0 ? "panel-default" : "panel-info")
with
@Html.Raw(@item.cy_year % 2 == 0 ? "panel-default" : "panel-info")
heres the code:
@{int i = 0;}
@foreach (var item in Model.Premium)
{
<div class="col-md-2">
<div class="panel @Html.Raw(i % 2 == 0 ? "panel-default" : "panel-info")">
<div class="panel-heading text-center">
<h1 class="panel-title" style="font-size: x-large; font-weight: 400">@item.year</h1>
</div>
<div class="panel-body text-center" style="font-size: x-large; font-weight: 300"> [email protected]</div>
</div>
</div>
i++;
}
Upvotes: 1
Reputation: 126
I recommend to do this like this. Instead JavaScript for every item.
@foreach (var item in Model.Premium)
{
<div class="col-md-2">
<div id="test" class="panel @((item.cy_year % 2 == 0) ? "panel-default" : "panel-info")">
<div class="panel-heading text-center">
<h1 class="panel-title" style="font-size:x-large;font-weight:400">@item.year</h1>
</div>
<div class="panel-body text-center" style="font-size:x-large;font-weight:300">
[email protected]
</div>
</div>
</div>
}
Upvotes: 0