Razor View Syntax doesn't recognize the “@” in an HTML attribute

你离开我真会死。 提交于 2020-01-03 10:58:32

问题


I am migrating a project from MVC 2 to MVC3 and the razor view engine.

In MVC 2, I would have the following html:

<div id="del_<%= Model.ActivityID.ToString() %>"></div>

When using razor, I tried the following, which renders the literal text "del_@Model.ActivityID.ToString()" when I want del_1.

<div id="del_@Model.ActivityID.ToString()"></div>

To get around the issue, I used:

<div id="@Model.ActivityID.ToString()_del"></div>

Is there away to make razor work with this syntax?

<div id="del_@Model.ActivityID.ToString()"></div>

回答1:


You'll have to use the @() around your particular model value like so:

<div id="del_@(Model.ActivityID.ToString())"></div>

The reason for this is because the del_@Model.ActivityID looks like an email address to the parser and by default the parser tries to ignore email addresses so you don't have to do something silly like john@@doe.com as emails are common enough that it would be annoying to do every time. So the people working on the razor parser just figured: "if it looks like an email, ignore it". So that's why you're having this particular issue.




回答2:


<div id="del_@(Model.ActivityID.ToString())"></div>

In case you didn't see the trick: use @( )



来源:https://stackoverflow.com/questions/4377317/razor-view-syntax-doesnt-recognize-the-in-an-html-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!