razor syntax - foreach loop

2019-03-17 10:27发布

@foreach (string s in "1,2,3".Split(',')) {
  s is equal to @s<br/>
}

I want to spit out: s is equal to 1 s is equal to 2 s is equal to 3

But I'm getting all sorts of errors because Visual Studio thinks that what is between the {}'s is code, but I want it to be markup.

标签: razor
3条回答
Juvenile、少年°
2楼-- · 2019-03-17 10:47

Just saw this on ScottGu's blog this morning: use @: before that line:

@foreach (string s in "1,2,3".Split(',')) {
  @: s is equal to @s<br/>
}

Alternately, use the <text /> tag:

@foreach (string s in "1,2,3".Split(',')) {
  <text>s is equal to @s<br/></text>
}
查看更多
趁早两清
3楼-- · 2019-03-17 10:50
@foreach (string s in "1,2,3".Split(',')) {
  <text>s is equal to </text>@s<br/>
}

I think it is because you are parsing text outside of brackets so Razor is thinking it is code, try using the razor text tag above, this parses exactly the same as @: but (for me at least) is a bit more intuitive (it won't parse the tags)

查看更多
等我变得足够好
4楼-- · 2019-03-17 11:05

Scott Guthrie just answered that this morning.
Change it to

@foreach (string s in "1,2,3".Split(',')) {
  @: s is equal to @s<br/>
}
查看更多
登录 后发表回答