Usage of the @ (at) sign in ASP.NET

4.36 (11 votes)

The number of places where you might use or encounter the @ sign in ASP.NET has grown over the last few years and its exact purpose in all circumstances still seems to cause confusion. Here's an overview of the most common places that it crops up, and guidance on its correct usage.

Razor Syntax

Razor was launched as a new templating syntax with the introduction of the ASP.NET Web Pages framework. A new view engine was added to MVC 3 that makes use of Razor. Razor enables mixing server-side code with HTML mark up to generate an HTML response that the framework sends to the browser. The @ sign has four uses in Razor:

  • To open a code block
  • To denote an inline expression or statement
  • To render the value of variables
  • To render single lines of content that contain plain text or unmatched HTML tags

Code blocks are sections of C# code that do not include any output to be rendered. They are usually positioned at the top of the Web Page or View and typically contain the logic for processing a page in Web Pages, or simple view-specific instructions in MVC. Code block start with the @ sign followed by an opening curly brace, and end with a closing curly brace:

@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_EditLayout.cshtml";
}

The content within the code block is standard C# code. A common mistake is to prefix variables declared within the code block with the @ sign. This is not necessary.

Inline expressions or statements are snippets of C# code appearing within HTML. Most often, these are used to make decisions on what to render based on conditions, or to iterate collections for display to the browser:

<ul>
    @foreach (var item in rows)
    {
        // do something
    }
</ul>

Nested expressions or statements do not start with an @ sign...

<ul>
    @foreach (var item in rows)
    {
        if (item.Equals(x))
        {
            // do something
        }
    }
</ul>

...unless they are separated from the outer expression or statement by unmatched tags

<ul>
    @foreach (var item in rows)
    {
        <li>
            @if (item.Equals(x))
            {
                // do something
            }
        </li>
    }
</ul>

The @ sign is used in Razor to render the value of variables, expressions and statements to the browser:

@DateTime.Now <!-- renders the current time to the browser -->

@(someCondition ? x : y) <!-- renders the value of x or y to the browser –>

@Html.ActionLink("Back to List", "Index") <!-- renders a hyperlink -->

Variables within expressions and statements should not be prefixed with the @ sign.

If you wish to render plain text or unmatched tags while inside a statement block, you use the @ sign followed by a colon to tell Razor that what follows is not C# code:

@if (item == x) // plain text
{
    @:The time is @DateTime.Now
}
@if (item == x) // unmatched tags
{
    @:<ul>
}
else
{
    @:<ol>
}

Identifiers

An identifier in C# is the name given to a namespace, class, variable, property, method, interface etc. Rules govern what makes a valid identifier. It is permitted to use a C# keyword as an identifier, but if you do, you must use the @ sign to prevent compile time errors. You are advised against using a keyword as an identifier, but there are times when you cannot avoid doing so.

Some overloads of the HtmlHelper classes (Web Pages and MVC) accept an object to represent the HTML attributes to be rendered as part of the tag that the helper represents. The following example adds a style attribute to a text input and sets its value to width:100%;:

@Html.TextBoxFor(model => model.FirstName, htmlAttributes: new { style = "width:100%;"})

When you do this, you are creating an anonymous type with a property called style to represent the HTML attributes. If you want to set the CSS class attribute via this method, you need to add a property to the anonymous type called class - which is a C# keyword. Therefore you must use the @ sign to enable the use of class in this case:

@Html.TextBoxFor(model => model.FirstName, htmlAttributes: new { @class = "full-width"})

A mistake I see repeated quite often in the ASP.NET forums is to apply the @ sign to all other properties of the anonymous type, which is just not necessary. Some people even think that the @ sign used here is part of the Razor syntax rules. It's not. It's usage here preceded Razor by a long way.

Verbatim String Literals

A verbatim string literal in C# consists of the @ sign followed by a literal string in double quotes and terminated with a semi-colon e.g.

var s = @"Hello World";

Two benefits of using a verbatim string literal include the fact that you only need to escape double quotes (by doubling them); and the string can span multiple lines in code without requiring continuation characters. For these reasons, verbatim string literals are most suitable for representing paths (which may otherwise need their slashes escaping) and regular expression patterns (which also may otherwise require backslashes to be escaped).

Regex re = new Regex(@"\w\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}\w");

They are also useful for representing large blocks of text if they need to be included in code in a readable manner, such as SQL statements that might be used in Web Pages applications:

var sql = @"SELECT 
                p.ProductName, 
                o.UnitPrice, 
                o.Quantity, 
                (o.UnitPrice * o.Quantity) - (o.UnitPrice * o.Quantity * o.Discount) As TotalCost 
            FROM OrderDetails o 
            INNER JOIN Products p ON o.ProductID = p.ProductID 
            WHERE o.OrderID = @0";

The use of the @ sign in this context once again has nothing to do with Razor syntax.

Summary

If you have ever wondered when and where you should be using the @ sign in your ASP.NET code, hopefully this article has helped to resolve your confusion.

 

You might also like...

Date Posted:
Last Updated:
Posted by:
Total Views to date: 19500

8 Comments

- Satyabrata

Refreshed a lot of things.Thanks

- AR Web

This is realy a nice article . Very well
explained . Thanks Sir..

- Steve

I was surprised I needed to use the @ before the html <fieldset> declaration in the following code:

@Using (Html.BeginForm())
@Html.AntiForgeryToken()
@Html.ValidationSummary()
@<fieldset>

I am still not sure why this is required, perhaps you could explain.

- Mike

@Steve,

Yours is an example of Visual Basic, whereas the article only looked at C# uses of the @ sign. The rules concerning Razor are slightly different between C# and VB. When you are inside a code block in VB and you want to render HTML, you need to prefix the opening tag with the @ sign.

- Joe Bedan

Cleared several things up for me. Thanks!

- Doan

As you wrote that the code within the code block is standard C# code.
But seem that i can not write a class within it.

- Mike

@Doan,

The code in a code block is standard C#, but the code block actually represents the body of a method - the WebPage class Execute method. You cannot declare a class in a method. It's not valid C#. The best place for declaring classes is in separate .cs files in App_Code. Then they are available throughout the application.

- Stephen

Awesome article. It seems Google prefers your blog over Microsoft documentation!

Recent Comments

Satyabrata Mohapatra 23/07/2017 16:43
In response to Razor Pages - The Elevator Pitch
@Dale Severin You can continue to build apps using asp.net web pages....

Satyabrata Mohapatra 23/07/2017 16:40
In response to Sending Email in Razor Pages
Thanks for sharing...learned a lot...

Gfw 22/07/2017 11:53
In response to Sending Email in Razor Pages
Question... Does System.Net.Mail support SSL?...

Dale Severin 20/07/2017 03:38
In response to Razor Pages - The Elevator Pitch
I work with razor web pages extensively. I appreciate the rapid development it permits me to I am as...

Obinna Okafor 14/07/2017 01:19
In response to Routing in Razor Pages
Thank you, Mike. Good post....

Satyabrata Mohapatra 11/07/2017 16:02
In response to Routing in Razor Pages
Very powerful routing system!!...

Cyrus 05/07/2017 03:41
In response to Razor Pages - Getting Started With The Preview
How can I trim packages and services as much as possible to use just razor pages? I don’t want to to...

Harris Boyce 04/07/2017 04:17
In response to Razor Pages - The Elevator Pitch
As a developer of a couple "trivial" web pages applications used by non-profits that wouldn't have I...

Cyrus 28/06/2017 20:25
In response to Razor Pages - Getting Started With The Preview
.net core 2.0 preview 2: <a...

ojorma 17/06/2017 09:24
In response to Razor Pages - The Elevator Pitch
Finally I can say goodbye to webforms...