开发者

Why isn't Razor recognizing a variable without wrapping it in parenthesis in some cases?

开发者 https://www.devze.com 2023-03-10 13:07 出处:网络
I have a section of Razor code in one of my views that isn\'t behaving the way I expect. The code in question contains multiple locations where I need to append the value of a variable from the Model

I have a section of Razor code in one of my views that isn't behaving the way I expect. The code in question contains multiple locations where I need to append the value of a variable from the Model onto an html attribute. The code below is a slightly simplified version of the markup on my page (I've removed some of the markup 'noise' that wasn't important to this example and just made the code harder to read).

There are three instances where I use @topic.StandardTopicId. The 1st and 2nd instances get replaced as I expected, but the 3rd instance name="IsCovered_@topic.StandardTopicId" renders without replacing the variable.

Code in question:

@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>
}

Sample of the output from the above code block:

...
<div id="frame-42" class="topic-frame">
    <label>
        <input type="radio" name="IsCovered_42" />
        No
    </lab开发者_如何转开发el>
    <label>
        <input type="radio" name="IsCovered_@topic.StandardTopicId" value="No" />
        Yes
    </label>
</div>
...

Can anyone explain why the last instance of the variable is not being replaced and is instead being rendered as is?


Razor will not parse the "@" in the middle of a word. The underscore is treated as part of a word as opposed to the dash. Use @() to place Razor code within words. @(topic.StandardTopicId)


Here's a reference to Razor syntax: C# Razor Syntax Quick Reference

Most likely, Razor considers IsCovered_@topic.StandardTopicId a valid e-mail address format, and therefore leaves it as-is.

0

精彩评论

暂无评论...
验证码 换一张
取 消