The closing braces of my C# code are not recognize

2019-06-11 10:17发布

问题:

I am working on a asp.net mvc 3 application. I use Razor for my views. I had this problem friday and thought I have fixed it but now I see that it was just some private case where the things worked for some reason.

I have a table with four columns, but each row may have different number of fields in one cell so I'm working on some sort of algorithm which will fill my cells with all the info that belong to them. This is what I have now :

@{
    int tempColumn = 1;    
}

<tr>
@foreach (var field in Model)
{   
    if (field != null)
    {   
        <td>    
        @for (int i = 0; i < field.Count; i++)
        {
            if (field[i].ColumnNo == tempColumn)
            {
                @field[i].QuestionText;
                @field[i].FieldValue;
            }
            else if (field[i] != null)
            {
                tempColumn++;
                @:</td>
                @:<td>
                @field[i].QuestionText;
                @field[i].FieldValue;
            }
        }
    }
    @:</td>      
}
</tr>

Basically the idea is that no matter how many pairs of @field[i].QuestionText; / @field[i].FieldValue; I have I will always have an opening <td> tag at the begining of the row and closing </td> tag at the end of the row. I have problems with the algorithm too but before I fix the issue with the not recognized closing bracelets I can't continue. So what is the error - when I try and run this code in debug mode I get this error :

The foreach block is missing a closing "}" character. Make sure you have a matching "}" character for all the "{" characters within this block, and that none of the "}" characters are being interpreted as markup.

But when I go to the code itself I get the same error about the if block and the for block. I thought that inserting the HTML <td> and </td> tags using this syntax - @: will keep the sructure of my C# code and just add the tags where I want them, but from what I think it seems that some reason at least one <td> or </td> tag is interpreted so that everything after it is recognized as HTML markup and not C# code. So what is the proper way to insert HTML markup in a C# method, or if the error is cause from something else - what could it be?

P.S

Any help about the algorithm would be appreciated though it's not the topic of this question.

回答1:

Change

            }
        }
    }
    @:</td>      
}
</tr>

to

            }
        }
        </td>      
    }
}
</tr>

You start your <td> inside the if (field != null) so you should end in inside there as well, otherwise if field == null you'll get <tr></td></tr>.