Escape @ character in razor view engine

2018-12-31 14:11发布

I am creating a sample ASP.NET MVC 3 site using Razor as view engine. The razor syntax starts with @ character e.g. @RenderBody(). If I write @test on my cshtml page it gives me parse error

CS0103: The name 'test' does not exist in the current context

How do I escape '@' character?

14条回答
爱死公子算了
2楼-- · 2018-12-31 14:47

just add a variable in CSHTML file var myVariable = @"@";

and add it to your layout <span class="my-class"><a href="@myVariale" target="_blank" >link text</a></span>

查看更多
旧人旧事旧时光
3楼-- · 2018-12-31 14:48

Instead of HTML entity I prefer the use of @Html.Raw("@")

查看更多
梦寄多情
4楼-- · 2018-12-31 14:50

Razor @ escape char to symbols...

<img src="..." alt="Find me on twitter as @("@username")" />

or

<img src="..." alt="Find me on twitter as @("@")username" />
查看更多
梦醉为红颜
5楼-- · 2018-12-31 14:50

@@ is the escape character for @ in Razor views as stated above.

Razor does however try to work out when an '@' is just an '@' and where it marks C# (or VB.Net) code. One of the main uses for this is to identify email addresses within a Razor view - it should not be necessary to escape the @ character in an email address.

查看更多
闭嘴吧你
6楼-- · 2018-12-31 14:51

You can use @@ for this purpose. Like var email = firstName + '\@@' + domain;

查看更多
回忆,回不去的记忆
7楼-- · 2018-12-31 14:58

@Html.Raw("@") seems to me to be even more reliable than @@, since not in all cases @@ will escape.

Therefore:

<meta name="twitter:site" content="@twitterSite">

would be:

<meta name="twitter:site" content="@Html.Raw("@")twitterSite">
查看更多
登录 后发表回答