45

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

@{
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>
            <img src="@Url.Content("~/Content/Images/Projects/")@item.Images.Where(i => i.IsMain == true).Select(i => i.Name).Single()" 
                alt="@item.Images.Where(i => i.IsMain == true).Select(i => i.AltText).Single()" class="thumb" />
        </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.

0

4 Answers 4

50

Just use this for the closing tag:

  @:</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.

3
  • 1
    Thanks. I tried @DJQuimby's solution and it somewhat worked but the else was no longer highlighted blue and I got this error "The code block is missing a closing "}" character. Make sure you have a matching "}" character for all the "{" characters within this block, and that none of the "}" characters are being interpreted as markup." Your solution worked though, thanks for both of your suggestions. Commented Mar 14, 2012 at 21:42
  • 1
    @Henk Holterman Thanks for answer. But in visual studio If I press ctrl + k + D to align code, It's reformatting it as @: (</tr> is moving to next line). So causing again same error Commented Mar 30, 2015 at 13:13
  • got a fix for this Pahul?
    – CularBytes
    Commented Dec 26, 2015 at 23:43
13

I would just go with

<tr @(if (count++ % 2 == 0){<text>class="alt-row"</text>})>

Or even better

<tr class="alt-row@(count++ % 2)">

this will give you lines like

<tr class="alt-row0">
<tr class="alt-row1">
<tr class="alt-row0">
<tr class="alt-row1">
3
  • Why do you have a <text> tag there? Commented Jul 14, 2017 at 5:52
  • 2
    Sorry, I found why: weblogs.asp.net/scottgu/… Commented Jul 14, 2017 at 5:56
  • This is great! Just wanted to add that the outer parenthesis, caused VS to indicate that if was an "invalid expression term". So I just took them off: <div class="row @if(cond){<text>...</text>}"> and it worked.
    – CPHPython
    Commented Jul 23, 2019 at 12:07
7

A little bit off topic maybe, but for modern browsers (IE9 and newer) you can use the css odd/even selectors to achieve want you want.

tr:nth-child(even) { /* your alt-row stuff */}
tr:nth-child(odd) { /* the other rows */ }

or

tr { /* all table rows */ }
tr:nth-child(even) { /* your alt-row stuff */}
2

To get rid of the if/else awkwardness you could use a using block:

@{
    var count = 0;
    foreach (var item in Model)
    {
        using(Html.TableRow(new { @class = (count++ % 2 == 0) ? "alt-row" : "" }))
        {
            <td>
                @Html.DisplayFor(modelItem => item.Title)
            </td>
            <td>
                @Html.Truncate(item.Details, 75)
            </td>
            <td>
                <img src="@Url.Content("~/Content/Images/Projects/")@item.Images.Where(i => i.IsMain == true).Select(i => i.Name).Single()" 
                    alt="@item.Images.Where(i => i.IsMain == true).Select(i => i.AltText).Single()" class="thumb" />
            </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>
        }
    }
}

Reusable element that make it easier to add attributes:

//Block is take from http://www.codeducky.org/razor-trick-using-block/
public class TableRow : Block
{
    private object _htmlAttributes;
    private TagBuilder _tr;

    public TableRow(HtmlHelper htmlHelper, object htmlAttributes) : base(htmlHelper)
    {
        _htmlAttributes = htmlAttributes;
    }

    public override void BeginBlock()
    {
        _tr = new TagBuilder("tr");
        _tr.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(_htmlAttributes));
        this.HtmlHelper.ViewContext.Writer.Write(_tr.ToString(TagRenderMode.StartTag));
    }

    protected override void EndBlock()
    {
        this.HtmlHelper.ViewContext.Writer.Write(_tr.ToString(TagRenderMode.EndTag));
    }
}

Helper method to make razor syntax clearer:

public static TableRow TableRow(this HtmlHelper self, object htmlAttributes)
{
    var tableRow = new TableRow(self, htmlAttributes);
    tableRow.BeginBlock();
    return tableRow;
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.