Sunil
Sunil

Reputation: 21406

Cannot get Razor syntax to work when nested Razor statements are there

I have following code in MVC4 ASP.Net with Razor engine, but there is some issue with the nested if for the 'tr' element.

Question: What would be the correct way of emitting the string "pink" if variable 'i' was even and if variable 'i' was odd then emit the string "white"? I wanted to use Razor syntax to do this rather than use even-odd CSS styling of tr.

   @{
        int i = 0;
    }
    @foreach (Product p in Model)
    {
        i++;

        <tr style="background-color:@if(i%2==0){"pink"} else { "white"})">
            <td>@p.Id</td>
            <td style="text-align:left;">@p.Name</td>
            <td style="text-align:left;">@p.Description</td>
            <td>@p.Price</td>
            <td>@p.UnitsInStock</td>
        </tr>
    }

Upvotes: 0

Views: 57

Answers (2)

user3559349
user3559349

Reputation:

@{
  int i = 0;
  var bc = "white";
}
@foreach (Product p in Model)
{
  if (i % 2 == 0)
  {
    bc= "pink";
  }
  <tr style="background-color:@bc" ...>

}

Upvotes: 1

Giannis Paraskevopoulos
Giannis Paraskevopoulos

Reputation: 18411

@(i % 2 == 0 ? "pink" : "white")

Upvotes: 1

Related Questions