Attempting to render a model object into a JSON structure via a partial, like this:
@if( Model.IsEmpty ) {
@( Model.UseNull ? "null" : "" )
} else {
@{ int i = 0; }
@foreach( var program in Model.Programs ) {
<text>
@(++i > 1 ? "," : "" )
{
"Id": "@program.ProgramId",
"Title": "@Html.Js( program.Title )",
"Url": "@Html.Js( program.Url )",
}
</text>
}
}
The page compiler complains on the foreach line, thinking the @ symbol is redundant. Removing it results in a compilation error on the line before. If I enclose the entire sections of the if/else in <text> blocks, it works.
Aside from using explicit text sections, is there a way to hint the compiler or escape the braces to avoid these errors?
Inside a code block, you cannot use
@characters to create more code blocks.Change your code to
However, you should use a JSON serializer instead.