Friday, 2 March 2012

Using the @ symbol in content with ASP.NET MVC3's Razor

Razor’s language parser is clever enough in most cases to infer whether a @ character within a template is being used for code or static content.  For example, below we're using a @ character as part of an email address:
An email was sent to edpitt@edpitt.com at: @DateTime.Now 

When parsing a file, Razor examines the content on the right-hand side of any @ character and attempts to determine whether it is C# code (if it is a CSHTML file) or VB code (if it is a VBHTML file) or whether it is just static content.  The above code will output the following HTML (where the email address is output as static content and the @DateTime.Now is evaluated as code:
An email was sent to edpitt@edpitt.com at: 3/2/2012 1:23:24 PM

In cases where the content is valid as code as well (and you want to treat it as content), you can explicitly escape out @ characters by typing @@.

No comments:

Post a Comment

Comments are moderated, so you'll have to wait a little bit before they appear!