在某些情况下,Razor为什么不识别变量而不将其包括在括号中?

Ham*_*359 3 asp.net-mvc razor asp.net-mvc-3

我的一个视图中有一段Razor代码,表现不像我期望的那样.有问题的代码包含多个位置,我需要将Model中的变量值附加到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>
}
Run Code Online (Sandbox Code Playgroud)

上述代码块的输出示例:

...
<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>
...
Run Code Online (Sandbox Code Playgroud)

任何人都可以解释为什么变量的最后一个实例没有被替换,而是被渲染为原样?

Jaz*_*ret 6

Razor不会在一个单词的中间解析"@".下划线被视为单词的一部分而不是短划线.使用@()将Razor代码放在单词中.@(topic.StandardTopicId)


Rya*_*ndy 5

以下是对Razor语法的引用:C#Razor语法快速参考

最有可能的是,Razor认为IsCovered_@topic.StandardTopicId有效的电子邮件地址格式,因此保持原样.