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?
In Razor, `@` symbol is used to transition from HTML to C#. To escape an '@' symbol in razor markup, use two '@' symbols.
Inside a code block, you cannot use @
characters to create more code blocks.
Change your code to
@if( Model.IsEmpty ) {
if (Model.UseNull) {
@:null
}
} else {
int i = 0;
foreach( var program in Model.Programs ) {
if (++i > 1) {
@:,
}
<text>
{
"Id": "@program.ProgramId",
"Title": "@Html.Js( program.Title )",
"Url": "@Html.Js( program.Url )",
}
</text>
}
}
However, you should use a JSON serializer instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With