John Shedletsky
John Shedletsky

Reputation: 7168

What are the rules for nesting @'s in Razor syntax?

I've just started with Razor (v3) and it's fine, but I don't understand the rules behind when you need to use the @ sign.

Here is an example from my current project.

In this code:

@if (ViewBag.ForcePublic == null && User.Identity.GetUserId() == @Model.Seller.Id)
        {                              
            <h2>Listing Status</h2>
            switch (Model.Status)
            {

If I put a @ in front of the switch statement, I get a runtime error saying that I don't need to nest @ signs.

However, in this code:

@if(!Model.BizAddress.StreetAddress.IsEmpty()) {
                 @Html.DisplayFor(model => model.BizAddress.StreetAddress);
            }

Not only do I not get a syntax error (as one would expect, considering the example above), if I don't include the @ sign in front of Html.DisplayFor, my StreetAddress is not printed. Instead it silently fails!

I would like to understand why this is happening so that I can avoid subtle bugs this might cause in the future.

I suspect that the root cause has something to do with the fact that the templating (I think) is analogous to a preprocessor step, and the scoping of the C# code is only known at runtime, so these two examples are structurally the same after both steps take place (preprocess, compile and run).

Upvotes: 0

Views: 504

Answers (1)

ataravati
ataravati

Reputation: 9145

@ in Razor is used for two different purposes:

1- You denote the start of a code block with Razor using a @ character. This is like <% %> in Web Forms.

2- Inline expressions (variables and functions) start with @ (for writing content on the page). This is like <%: %> or <% Response.Write() %> in Web Forms.

In your code, the @ character before if denotes the start of a code block. The end of the block is the end } of the if block. You don't need to and are not allowed to use @ for anything in between. But, the @ before Html.DisplayFor() is used for an inline expression. In fact, you should not put a semi-colon at the end of that line, otherwise the semi-colon will be displayed after the display name on the page.

Look at this quick reference for more details.

Upvotes: 1

Related Questions