Jake Pearson
Jake Pearson

Reputation: 27757

Does anyone know why this Razor code is not compiling?

Could someone help me get this razor syntax snippet to compile?

@var count = 0;
@foreach (var column in Enumerable.Range(0, 20).Select(i => "Title " + i) {
    if(count % 5 == 0) { 
        <tr>
    }
    <td>@column</td>
    @if(count % 5 == 4) {
        </tr>
    }
    count++;
}

Upvotes: 2

Views: 2212

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039438

@{
    var count = 0;
}
@foreach (var column in Enumerable.Range(0, 20).Select(i => "Title " + i)) 
{
    if(count % 5 == 0) 
    { 
        @:<tr>
    }
    <td>@column</td>
    if(count % 5 == 4) 
    {
        @:</tr>
    }
    count++;
}

Upvotes: 2

Lasse Espeholt
Lasse Espeholt

Reputation: 17792

You do not need the count variable. I've made an alternative solution to Darin´s answer:

@foreach (var pair in Enumerable.Range(0, 20).Select(i => new { Title = "Title " + i, Index = i }))
{
    if(pair.Index % 5 == 0) { 
        @:<tr>
    }
    <td>@pair.Title</td>
    if(pair.Index % 5 == 4) {
        @:</tr>
    }
}

As you can see in Darin´s answer and this answer, you don't need @ when you are inside a block. Furthermore, your <tr> and </tr> look "uneven" to the compiler, so we have to force these with @:<tr>. And last, @var count = 0 will have to be in a block like @{var count = 0}.

Update: If you actually need an index (if you're not using Range()) then you can do as follows (using the overload of Select which generates an index for each item):

@foreach (var pair in yourSource.Select((data, i) => new { Title = "Title " + data, Index = i }))

Upvotes: 4

Related Questions