Reputation: 35
I have a small program that is working (mostly). It's returning an Item Code from a database and returning a quantity for that code. I then have a @foreach block of code in Razor to dynamically create divs that contain the name and quantity. In the rest of the code there are Knockout functions to update the display automatically. However... the issue I'm having is trying to apply a different background colour to each div.
@foreach (var x in Model.Quantities)
{
int itemCode = x.ItemEncode;
string itemName = "";
int quantity = x.Quantity;
switch (itemCode)
{
case 11:
<style>.getcolour {background-color: blue}</style>
itemName = "Item A";
break;
case 12:
<style>.getcolour {background-color: skyblue}</style>
itemName = "Item B";
break;
case 21:
<style>.getcolour {background-color: red}</style>
itemName = "Item C";
break;
case 31:
<style>.getcolour {background-color: pink}</style>
itemName = "Item D";
break;
case 41:
<style>.getcolour {background-color: purple}</style>
itemName = "Item E";
break;
case 61:
<style>.getcolour {background-color: green}</style>
itemName = "Item F";
break;
}
<div class="getcolour">
<h3>@Html.Raw(itemName)</h3>
<hr />
<h2>@Html.Raw(quantity)</h2>
</div>
}
The itemNames and Quantities display correctly so the foreach block is working but every div is rendered with the last colour (green) in the Switch statement. Any advice on applying the colours correctly will be much appreciated.
Upvotes: 1
Views: 1716
Reputation: 81
Please try this.
@foreach (var x in Model.Quantities)
{
int itemCode = x.ItemEncode;
string itemName = "";
int quantity = x.Quantity;
string bgColor = "";
switch (itemCode)
{
case 11:
bgColor = "blue";
itemName = "Item A";
break;
case 12:
bgColor = "skyblue";
itemName = "Item B";
break;
case 21:
bgColor = "red";
itemName = "Item C";
break;
case 31:
bgColor = "pink";
itemName = "Item D";
break;
case 41:
bgColor = "purple";
itemName = "Item E";
break;
case 61:
bgColor = "green";
itemName = "Item F";
break;
default: break;
}
<div style="background-color:@bgColor">
<h3>@Html.Raw(itemName)</h3>
<hr />
<h2>@Html.Raw(quantity)</h2>
</div>
}
Upvotes: 1