ASP.NET Razor HTML - Change the background color of a tables row depending on a value
Just use the requestStatus as you class name and assign styles as appropiate:
<style type="text/css">
.grey {
background-color:grey;
}
.approved {
background-color:green;
}
.rejected {
background-color:red;
}
.pending {
background-color:lime;
}
</style>
<fieldset>
<legend>Your Leave Requests</legend>
<table border="1" width="100%">
<tr class="grey">
<th>Description</th>
<th>Leave Type</th>
<th>Start Date</th>
<th>End Date</th>
<th>Total days leave requested</th>
<th>Request Status</th>
</tr>
@foreach (var rows2 in rows1)
{
<tr class="@rows2.requestStatus">
<td>@rows2.description</th>
<td>@rows2.leaveType</th>
<td>@rows2.startDate.ToString("dd-MMMM-yyyy")</th>
<td>@rows2.endDate.ToString("dd-MMMM-yyyy")</th>
<td>@rows2.totalDays</th>
<td>@rows2.requestStatus</th>
</tr>
}
</table>
</fieldset>
Your razor should look something like this:
Your Leave Requests
<tr bgcolor="grey">
<th>Description</th>
<th>Leave Type</th>
<th>Start Date</th>
<th>End Date</th>
<th>Total days leave requested</th>
<th>Request Status</th>
</tr>
@foreach (var rows2 in rows1)
{
@
{
var statusClass = "colorA";
if (rows2.requestStatus == "pending")
{
statusClass = "colorB";
}
}
<tr class="@statusClass">
<td>@rows2.description</td>
<td>@rows2.leaveType</td>
<td>@rows2.startDate.ToString("dd-MMMM-yyyy")</td>
<td>@rows2.endDate.ToString("dd-MMMM-yyyy")</td>
<td>@rows2.totalDays</td>
<td>@rows2.requestStatus</td>
</tr>
}
</table>
</fieldset>
Then you need to have some classes specified in your css:
.colorA {background-color: red}
.colorB {background-color: green}
That answers your question based on your code. A better practice, imo, would be to put a statusClass property on your row2 object model. Then, in your logic, set this based on whatever logic you need and, instead of having that "if" statement and variable, just set the tr class directly, like this:
<tr class="@row2.statusClass">