Razor and the @ symbol

Another programmer asked me about when you use the @ symbol in Razor. This was my reply…

The @ sign is used for switching in and out of code. It is a razor thing – a bit like for most things. It can be used in the following ways (might be others I have missed too): –

To set the ModelType at the top
You can add in a block of code with
@Code

End Code
When you are in HTML, to call a function that outputs HTML or text
It usually works out where the end of the function call is by itself and switches back to HTML
If it doesn’t get it right, you can put brackets in – eg. @(Now.ToString(“dd/MM/yyyy”))
You can also use it to include an If/Using/With/loop in HTML – eg.

@For Each o in Orders
@

Next

When you are in code, to switch back to HTML, by placing it before an HTML tag
eg.
For Each o in Orders
@

Next
If you don’t want to output an HTML tag, you can use @ to switch back
When you are in code, you can use it to write the output of a function into the HTML – eg.

For Each o in Orders
@o.CustomerName @
Next

It is worth noting that you can call these functions from within code – eg. Html.LabelFor, but if you don’t stick the @ on the beginning, they won’t get written to the HTML – the result won’t go anywhere!

Also worth pointing out that you can nest back and forwards between HTML and code – eg..

@Code
If Model.Data.Count>0 Then
@

@For Each o in Model.Data
@


Next

Order ID Customer Name
@o.ID @o.Customer.Name

Else
@No results
End If
End Code

Leave a Reply