The problem with your code is with the lines:
int j = 0;
for(; j < Model.Items[i].SubCount; j++) {
These lines are not interpreted as Razor, but as raw text. This results in the variable j
not being declared or defined on the line:
<dd>@(Model.Items[i].Sub[j].Name)
The reason is that you need to be in a code context to be able to write C# code. You do that by using the @
sign, but that only interprets a single expression as code. It doesn't switch to a code context. So you can't use the @ sign if you want to write multiple lines of code. If you want to do that, you need to enter a code context by using braces, prepended by an @ sign: @{ }
.
Try this instead:
<tbody>
@for(int i = 0; i < @Model.ItemsCount; i++) {
<tr>
<td>@(i+1)</td>
<td>
@Model.Items[i].Name
@{
int j = 0;
for(; j < Model.Items[i].SubCount; j++) {
<dd>@(Model.Items[i].Sub[j].Name)
}
}
</td>
<td>@Model.Items[i].CountStr</td>
<td>@Model.Items[i].CostStr</td>
<td>@Model.Items[i].TotalStr</td>
</tr>
}
</tbody>
Alternatively, you can declare and initialize the j
variable in the for
loop, and tell the Razor compiler that the for
loop is code, by prepending it with an @
sign. Like this:
<tbody>
@for(int i = 0; i < @Model.ItemsCount; i++) {
<tr>
<td>@(i+1)</td>
<td>
@Model.Items[i].Name
@for(int j = 0; j < Model.Items[i].SubCount; j++) {
<dd>@(Model.Items[i].Sub[j].Name)
}
</td>
<td>@Model.Items[i].CountStr</td>
<td>@Model.Items[i].CostStr</td>
<td>@Model.Items[i].TotalStr</td>
</tr>
}
</tbody>
I would recommend you to follow the last example.
You can check out Phil Haack's Razor quick reference for some examples of how the Razor syntax works.
And by the way, it's invalid HTML to have an <dd>
tag if it's outside a <dt>
list. So you might want to reconsider your HTML structure. You can read the documentation on the <dd>
tag on MDN.