Does a foreach loop work?

Mar 7, 2011 at 11:02 AM
Edited Mar 7, 2011 at 11:03 AM

Hello,

I tried to use a foreach loop to parse a template, but it fails:

 

@foreach (var p in Model.Addresses)
{
     foo
}

 

The error was something about a expected semilicon. Perhaps the parser tries 'foo' to interpret as a command?
The same loop with @p instead of foo works.

 

@foreach (var p in Model.Addresses)
{
     @p
}

 

Can you help me? Razor would be nice as a generic templating engine :D

Coordinator
Mar 7, 2011 at 11:34 AM
Edited Mar 7, 2011 at 11:35 AM

Hi,

Razor's markup parser supports XML-like syntax, and as such is expecting an xml element, OR code. It's smart enough to figure which is which, unless in the circumstance you have detailed above, where it is not expecting straight text. If you're not wrapping your "foo" in an xml element, Razor does support a default wrapping element "<text>" which should be used in this scenario:

 

@foreach (var p in Model.Addresses)
{
    <text>foo</text>
}
Coordinator
Mar 7, 2011 at 2:03 PM

You can also use:

 

@foreach (var p in Model.Addresses) {
    @:foo
}

Mar 7, 2011 at 5:41 PM

Thanks, this does work!

Funny, yesterday i couldn't find anything about it and just after reading your responses i stumbled over the answer on Stackoverflow.... anyhow, thanks alot for the fast answer!