I’m trying to conditionally add a CSS background-color to a set of table rows, based on how close the item’s expiry date is. Thirty days or less should be red, 90 – 31 days amber and the rest green. (I’m putting the red in first, once this is working I’ll go back and do the amber/green rows).
@foreach (var item in Model)
{
int daysLeft = (item.ExpiryDate - DateTime.Today).Days;
if (daysLeft <= 30)
{
<tr style="background-color:Red">
}
else
{
<tr>
}
<td>
@Html.DisplayFor(modelItem => item.SupplierName)
</td>
<td>
@Html.DisplayFor(modelItem => item.ExpiryDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.InceptionDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.Value)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
@Html.ActionLink("Details", "Details", new { id = item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
</tr>
}
When I run this page, I get a YSOD saying the @foreach block is missing its closing }, but as far as I can see they are matched so I’m assuming the actual problem is something else.
Razor requires that tags directly inside code blocks be balanced and well-formed.
Therefore, all of the code after the first opening
<tr>tag is actually parsed as markup, so that the final}just closes theif.To fix that, you can force Razor to ignore the tag by prefixing the line with
@:.Alternatively, you can get rid of the
ifentirely and write