2

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?

Tasos K.
  • 7,979
  • 7
  • 39
  • 63
Dbloom
  • 1,302
  • 3
  • 18
  • 45
  • Make a variable like `string classvar = "warning";` and then add that to your `tr`. And in the if statement just change the value of `classvar = "";` in your else. See this as an example: http://stackoverflow.com/questions/8061647/conditional-html-attributes-using-razor-mvc3 – Nico Apr 13 '15 at 19:30
  • Can you show your complete section of code (including the end of the foreach and the ``? – Erik Funkenbusch Apr 13 '15 at 19:32

2 Answers2

10

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

Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291
3

My guess is that the </tr> is somehow misplaced and that is why you get the error.

You could replace your if statement with the use on an inline if. This will make your HTML to be easier to read, and eventually maintain.

<tr class="@((item.CurrentTime < DateTime.Now.AddHours(-4) ? "warning" : ""))">
    <!--- Your row contents -->
</tr>
Tasos K.
  • 7,979
  • 7
  • 39
  • 63