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.
Just use this for the closing tag:
And leave your if/else as is.
It works fine. You're working in 2 language-spaces here, it seems only proper not to split open/close sandwiches over the border.
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.
or
I would just go with
Or even better
this will give you lines like
To get rid of the if/else awkwardness you could use a using block:
Reusable element that make it easier to add attributes:
Helper method to make razor syntax clearer: