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.
Razor syntax is a simple programming syntax for embedding server-based code in a web page. In a web page that uses the Razor syntax, there are two kinds of content: client content and server code.
Inline expression. Start with @ symbol to write server-side C# or VB code with HTML code. For example, write @Variable_Name to display the value of a server-side variable, e.g., DateTime. Now returns the current date and time.
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.
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"> 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With