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:59

I couldn't get any of these to work inside my placeholder attribute, so I used xml special character.

<input type="text" placeholder="fex: firstname&#64;lastname.com"/>

See more examples here. https://www.dvteclipse.com/documentation/svlinter/How_to_use_special_characters_in_XML.3F.html

查看更多
步步皆殇っ
3楼-- · 2018-12-31 15:01

I just had the same problem. I declared a variable putting my text with the @.

@{
   var twitterSite = "@MyTwitterSite";
}

...

<meta name="twitter:site" content="@twitterSite">
查看更多
妖精总统
4楼-- · 2018-12-31 15:04

I tried all the options above and none worked. This is what I did that worked :

@{
    string str = @"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$";
}

<td>Email</td>
<td>
   <input type="text" id="txtEmail" required name="email" pattern=@str /> 
</td>

I created a string varible and passed all the RegEx pattern code into it, then used the variable in the html, and Razor was cool with it.

查看更多
皆成旧梦
5楼-- · 2018-12-31 15:07

@@ should do it.

查看更多
谁念西风独自凉
6楼-- · 2018-12-31 15:08

Actually @ should be used with the Razor syntax Keywords or to the variable/model to bind a Value.

For Eg: if test is assigned with value i.e @ { var test = "ABC" } then you can get the value by settings as @test anywhere is cshtml page in html part. otherwise, simple use as @Html.DisplayName("test")

查看更多
浅入江南
7楼-- · 2018-12-31 15:09

use <text></text> or the easier way @:

查看更多
登录 后发表回答