I’ve recently upgraded a project from MVC 1 to MVC 3 and now I’m trying out Razor.
In one View, I have a foreach code block, but the nested if statement does not seem to want the @ in front of it.
My original code was:
@foreach(var r in Model.Results)
{
string css = r.Result.Count() > 0 ? "fail" : "pass";
<p class="@css"><strong>@r.Description</strong></p>
@if(r.Result.Count() > 0)
{
<p>Count: @r.Result.Count()</p>
<table>
<thead>
<tr>
<th>ID</th><th>Title</th><th>Description</th>
</tr>
</thead>
<tbody>
@foreach(var e in r.Result) {
<tr><td>@e.Id</td><td>@e.Title</td><td>@e.Description</td></tr>
}
</tbody>
</table>
}
}
I’ll get a runtime error with @if that says: Unexpected “if” keyword after “@” character. Once inside code, you do not need to prefix constructs like “if” with “@”.
If I remove the @ the code runs fine. I expected to need the @ because of the HTML immediately preceding it. What confuses me more is that I do need the @ before the nested foreach. What are the rules in play here?
The nested
foreachis inside of HTML (which happens to be inside of other code).To go from markup to code, you need an
@.It’s only unnecessary when directly nesting code blocks.