Thomas H
Thomas H

Reputation: 902

How to properly escape braces in 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?

Upvotes: 5

Views: 5182

Answers (2)

SLaks
SLaks

Reputation: 887767

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.

Upvotes: 7

Adam Price
Adam Price

Reputation: 10257

Using JavaScriptSerializer to convert the model object into JSON is probably a better idea than this method.

In my project, I've even made it an HtmlHelper, like so:

private static readonly JavaScriptSerializer JsonSerializer = new JavaScriptSerializer();
public static HtmlString ToJson<T> (this HtmlHelper htmlHelper, T obj)
{
    return new HtmlString(JsonSerializer.Serialize(obj));
}

You could then use it in your View, like:

<script type="text/javascript">
    var model = @Html.ToJson(Model);
</script>

Upvotes: 3

Related Questions