Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple If/Else Razor Syntax

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.

like image 970
Shane LeBlanc Avatar asked Mar 14 '12 21:03

Shane LeBlanc


People also ask

What is the Razor syntax?

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.

How do you write HTML code in razor view?

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.


2 Answers

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.

like image 118
Henk Holterman Avatar answered Sep 20 '22 12:09

Henk Holterman


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"> 
like image 22
Jeff Avatar answered Sep 23 '22 12:09

Jeff