razor syntax - foreach loop

Razor

Razor Problem Overview


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


Solution 1 - Razor

Just saw this http://weblogs.asp.net/scottgu/archive/2010/12/15/asp-net-mvc-3-razor-s-and-lt-text-gt-syntax.aspx">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>
}

Solution 2 - Razor

Scott Guthrie just answered that this morning.
Change it to

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

Solution 3 - Razor

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIan DavisView Question on Stackoverflow
Solution 1 - RazorDomenicView Answer on Stackoverflow
Solution 2 - RazorSLaksView Answer on Stackoverflow
Solution 3 - RazorPharabusView Answer on Stackoverflow