Dbloom Dbloom - 1 month ago 8
C# Question

With MVC, how can I format <tr> with a certain class based on the date contained in one of the <td>?

I have an MVC application that displays the progress of Windows deployments. In my view, I have a table that displays the current status of each deployment. One of those properties is the last time the deployment checked in ('CurrentTime'). I want to change the style of the if the CurrentTime is more than 4 hours ago.

In my MVC view, I am trying to do something like this:

@foreach (var item in Model)
{
if(item.CurrentTime < DateTime.Now.AddHours(-4))
{
@:<tr class="warning">
}
else
{
@:<tr>
}


This is not working. I am getting a parser error:


Encountered end tag "tr" with no matching start tag. Are your start/end tags properly balanced?


What is a simple way (I am just learning MVC/web programming) to accomplish this?

Answer

The easiest way to do this (and cleaner) is to do something like this:

@foreach (var item in Model)
{
    var warning = item.CurrentTime < DateTime.Now.AddHours(-4) ? "warning" : null;
    <tr class="@warning">
       <td></td>
    </tr>
}

One nice feature of Razor 2+ is that it will automatically remove class attributes if the value is null. This feature is called "Conditional Attributes", and you can read more here if you want.

http://www.davidhayden.me/blog/conditional-attributes-in-razor-view-engine-and-asp.net-mvc-4

Comments