Home Simple If/Else Razor Syntax
Post
Cancel

Simple If/Else Razor Syntax

I was looking for solving this error:

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

and StackOverflow helped me, again.

Simple If/Else Razor Syntax

I’m trying to do a simple If/Else within a foreach with this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@{
var count = 0;
    foreach (var item in Model)
    {
        if (count++ % 2 == 0)
        {
            @:<tr class="alt-row">
        } else { 
            @:<tr>
        }
            <td>
                @Html.DisplayFor(modelItem => item.Title)
            </td>
            <td>
                @Html.Truncate(item.Details, 75)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id=item.ProjectId }) |
                @Html.ActionLink("Details", "Details", new { id = item.ProjectId }) |
                @Html.ActionLink("Delete", "Delete", new { id=item.ProjectId })
            </td>
        </tr>
    }
}

I get a parse error Encountered end tag "tr" with no matching start tag. Are your start/end tags properly balanced?. Seems like the if statement doesn’t wanna’ work.

Answer

Just use this for the closing tag:

1
  @:</tr>

And leave your if/else as is.

Seems like the if statement doesn’t wanna’ work.

It works fine. You’re working in 2 language-spaces here, it seems only proper not to split open/close sandwiches over the border.

This post is licensed under CC BY 4.0 by the author.