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.
The if statement returns true or false, based on your test: The if statement starts a code block. The condition is written inside parenthesis. The code inside the braces is executed if the test is true.
razor helps you embed serverside code like C# code into web pages. cshtml is just a file extension. razor view engine is used to convert razor pages(. cshtml) to html.
The @ symbol is used in Razor initiate code, and tell the compiler where to start interpreting code, instead of just return the contents of the file as text. Using a single character for this separation, results in cleaner, compact code which is easier to read.
To declare a variable in the View using Razor syntax, we need to first create a code block by using @{ and } and then we can use the same syntax we use in the C#. In the above code, notice that we have created the Code block and then start writing C# syntax to declare and assign the variables.
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 the if
.
To fix that, you can force Razor to ignore the tag by prefixing the line with @:
.
Alternatively, you can get rid of the if
entirely and write
string style = daysLeft <= 30 ? "background-color:Red" : null; <tr style="@style"> ... </tr>
Use the conditional operator
bool condition ? true_expression : false_expression;
http://msdn.microsoft.com/en-us/library/ty67wk28(v=vs.80).aspx
@foreach (var item in Model) { int daysLeft = (item.ExpiryDate - DateTime.Today).Days; <tr style="@(daysleft < 30 ? "Background-color:red" : "")"> ..... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With