Reputation: 7
I have got a list and I want to apply a different style to each item depending on it's Id. Below is my attempt to do that but unfortunately something is wrong. Any help will be very appreciated.
@foreach (var item in Model)
{
@if (@item.Id==0)
{
var css = "background-color:Aqua";
}
else if (@item.Id==1)
{
var css = "background-color:Red";
}
else
{
var css = "background-color:Green";
}
<div style="@css" class="box">
@item.Info
</div>
<div>
@item.Name
</div>
}
Upvotes: 0
Views: 83
Reputation: 218842
Your if
condition is already in a code block(foreach code..
). So no need of @
. Also define the css
varibale outside of your if-else
blocks
@foreach (var item in Model)
{
var css="background-color:Green";
@if (@item.Id==0)
{
css = "background-color:Aqua";
}
else if (@item.Id==1)
{
css = "background-color:Red";
}
<div style="@css" class="box"> @item.Info </div>
<div> @item.Name </div>
}
Another solution is creating a css class name string inside your loop using your item.Id
or item.Code
(if that exists) and using that in your markup. With this approach, you may completely eliminate the if condition checking in your razor code, thus making this a much cleaner solution than the previous one.
@foreach (var item in Model)
{
<div class="box [email protected]">
@item.Name
</div>
<div> @item.Name </div>
}
And in your css class add the css classes as needed
.myClass-0
{
background-color:aqua;
}
.myClass-1
{
background-color:red;
}
.myClass-2
{
background-color:green;
}
Id's might change, so i recommend using some other properties like Code/Name etc.
Upvotes: 1
Reputation: 5755
First of all try setting a default style and bring var css
out of the if block, then set the value according to your needs.
But you can also try a helper for that:
@helper styler(int id, String value){
var bg = "background-color:white" // as default
if(id == 1){
bg = "Another color";
}
else if (id == 2) {
// continue setting values
}
<span style="@bg">@value</span>
}
However, this is not really necessary as you can set the style inside of the for loop, but this approach reduce some code duplication.
Upvotes: 0