问题
I'm trying to make a very simple view using Razor syntax in MVC3, but it seems I can't get the syntax right.
I have a simple table like this
<table>
<tr>
@{
var counter = 0;
}
@foreach (var category in ViewBag.Categories)
{
counter++;
<td>
<input type="checkbox" checked="checked" name="@("category" + category.Code)" />
@category.Description
</td>
if (counter % 2 == 0)
{
</tr>
<tr>
}
}
</tr>
</table>
When I insert the and inside the if-statement, I receive this error
The using block is missing a closing "}" character.
If I try to wrap those two tags inside and , I get this error instead:
The "tr" element was not closed.
回答1:
Your </tr><tr>
messes up the "flow" of the html/code mix.
You are closing the tr-tag on a different level, not a different level in the html, but inside the code. You should trick razor into outputting html, that it does not parse itself.
You could include them like this:
@:</tr><tr>
or
@Html.Raw("</tr><tr>")
The result:
if (counter % 2 == 0)
{
@:</tr><tr>
}
Click for Haack's quick reference of Razor syntax
回答2:
I would say you're missing the @ in front of the if statement. Try @if(counter % 2 == 0)
.
Hope that helps.
Update
I checked it out and the answer from GvS seems to work just fine. The @ is not necessary for the if statement.
@for (int i = 0; i < 5; i++)
{
if (i == 3)
{
@:</tr><tr>
}
}
回答3:
You are mixing HTML and code in the foreach. That's why you get problems.
Either use <text></text>
block around the HTML, or do the following:
<table>
<tr>
@{
var counter = 0;
}
@foreach (var category in ViewBag.Categories)
{
@{
counter++;
}
<td>
<input type="checkbox" checked="checked" name="@("category" + category.Code)" />
@category.Description
</td>
@if (counter % 2 == 0)
{
</tr>
<tr>
}
}
</tr>
</table>
来源:https://stackoverflow.com/questions/4827354/mvc3-razor-syntax-troubles