Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly escape braces in Razor

Tags:

razor

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?

like image 738
Thomas H Avatar asked Apr 07 '11 22:04

Thomas H


People also ask

How do you escape the @- symbol in a razor view?

In Razor, `@` symbol is used to transition from HTML to C#. To escape an '@' symbol in razor markup, use two '@' symbols.


1 Answers

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.

like image 123
SLaks Avatar answered Sep 25 '22 09:09

SLaks