开发者

Does anyone know why this Razor code is not compiling?

开发者 https://www.devze.com 2023-03-09 06:49 出处:网络
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) {

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&开发者_运维问答gt;
    @if(count % 5 == 4) {
        </tr>
    }
    count++;
}


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 }))


@{
    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++;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消