在我的一个 View 中,我有一段 Razor 代码的行为不符合我的预期。有问题的代码包含多个位置,我需要将模型中的变量值附加到 html 属性上。下面的代码是我页面上标记的略微简化版本(我删除了一些对本示例不重要的标记“噪音”,只是使代码更难阅读)。
我在三个实例中使用 @topic.StandardTopicId
.第一个和第二个实例如我所料被替换,但第三个实例 name="IsCovered_@topic.StandardTopicId"
在不替换变量的情况下呈现。
有问题的代码:
@foreach(var topic in Model.Group) {
<div id="frame-@topic.StandardTopicId" class="topic-frame">
<label>
<input type="radio" name="IsCovered_@(topic.StandardTopicId)" />
No
</label>
<label>
<input type="radio" name="IsCovered_@topic.StandardTopicId" />
Yes
</label>
</div>
}
上述代码块的输出示例:
...
<div id="frame-42" class="topic-frame">
<label>
<input type="radio" name="IsCovered_42" />
No
</label>
<label>
<input type="radio" name="IsCovered_@topic.StandardTopicId" value="No" />
Yes
</label>
</div>
...
谁能解释为什么变量的最后一个实例没有被替换而是按原样呈现?
最佳答案
Razor 不会解析单词中间的“@”。与破折号相反,下划线被视为单词的一部分。使用 @() 将 Razor 代码放在单词中。 @(topic.StandardTopicId)
关于asp.net-mvc - 为什么在某些情况下 Razor 不能识别变量而不用括号括起来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6219322/