Razor ViewEngine: How do I escape the "@" symbol?

asp.netasp.net Mvc-3RazorEscapingTwitter Anywhere

asp.net Problem Overview


I'm trying to output some Twitter handles in ASP.NET MVC3 in conjunction with the Twitter @Anywhere API, and I haven't been able to figure out how to actually escape the "@" symbol in a Razor view.

Does anyone know what the syntax is for escaping the "@" character in Razor?

I've tried using <text></text> and that results in a JIT error.

asp.net Solutions


Solution 1 - asp.net

You have to use @@ to escape the @ symbol.

One important thing to notice is that you DO NOT need to escape the @ symbol when it exists within an email address. Razor should be smart enough to figure that out on its own.

Solution 2 - asp.net

If you are adding Twitter meta tags

and your Twitter username is, say, foobar

it should look like this

<meta name="twitter:site" content=@("@foobar")>

Solution 3 - asp.net

if you need to comment @ symbols in css code and just @@ wont work, use this:

@("@@font-face"){ ... css ...}

Solution 4 - asp.net

I had yet another odd case: pass '@' + @Model.SomeProperty to a link href.

The best solution for this case was given IMO in this answer to a similar question. Both @@ and @: didn't work while using the html code &#64; would complicate things.

So, my code was <a href="~/path/?query=@('@')@Model.SomePropery">

@Html.Raw('@')@Model.SomePropery would have worked as well.

Solution 5 - asp.net

If you are adding Schema.org JSON-LD Tags, @Matt's answer worked for me:

  ....
  @("@context"): "https://schema.org",
  ....

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAarononthewebView Question on Stackoverflow
Solution 1 - asp.netJasCavView Answer on Stackoverflow
Solution 2 - asp.netMattView Answer on Stackoverflow
Solution 3 - asp.netLin-ArtView Answer on Stackoverflow
Solution 4 - asp.netTiberiu CraciunView Answer on Stackoverflow
Solution 5 - asp.netJClarkCDSView Answer on Stackoverflow