asp.net-mvc - @: in a foreach loop doesn't work when it's between tags?
问题描述
I know that @:
is for output a single line of content containing plain text or unmatched HTML tags;
If so , why do I get an error for :
( ":" is not valid at the start of a code block. Only identifiers, keywords, comments, "(" and "{" are valid.)
@foreach (int line in new int[] { 0, 1 })
{
<span>
@: aaaaa
</span>
}
While this run as expected :
@foreach (int line in new int[] { 0, 1 })
{
@: aaaaa
}
解决方案
@:
is used to mix text within a code block.
When you use the span
tag or any other html elements, inside a C# code block, you are already mixing HTML tag and razor can properly parse and execute it. When you use @:
inside an HTML element (non-code block), it is not even valid.
In short, you can use HTML elements inside a code block as wrapper to mix plaintext/html.
@foreach (int line in new int[] { 0, 1 })
{
<div>Hello</div>
}
In razor, the @:
tag produce the same result as the text
tag when it comes to mixing plain text within a code block. The below will also produce same result as your second code block.
@foreach (int line in new int[] { 0, 1 })
{
<text>aaa533</text>
}
推荐阅读
- java - 可以同时使用executeQuery 和executeBatch,每个连接一个连接吗?
- django - Django Import Export,过滤连接到用户的ForeignKey对象
- html - SVG 图像未在网页上完全显示
- c++ - 为什么我的代码即使在我尝试声明它之后仍说它的类型不完整?
- mongodb - 可以使用解析服务器进行*反向*关系查询吗?
- java - SpringWebFlux 安全性 - 在会话中更新身份验证详细信息
- visual-studio-code - 如何使 VSCode 的终端使用 zsh for Windows 打开目录路径?
- python - 使用 cv2.imwrite、f'string 在 for 循环内保存多个版本的 img
- windows - 使用“1”参数调用“DownloadString”的异常
- sql - 当存在多个 JOIN LATERAL 时优化慢查询