Kelly Cline
Kelly Cline

Reputation: 2246

Difference between Razor single statement and block

Why does the first segment work and the second throw an "Invalid expression term '<' error at the label tag?

First segment:

@foreach( var f in new List<List<string>>{ new List<string>{ new List<string>{ "PumpSize", "Pump Size" },
new List<string>{ "PumpType", "Pump Type" }, 
new List<string>{ "WellHead", "Well Head" } } )
{
    <label>@f[1]
    </label>
}

Second segment:

@{
    var fields = new List<List<string>>{ new List<string>{ new List<string>{ "PumpSize", "Pump Size" },
        new List<string>{ "PumpType", "Pump Type" }, 
        new List<string>{ "WellHead", "Well Head" } };
    fields.ForEach( f => 
    {
        <label>@f[1]</label>
    } );
}

The error I get is with the <label>, "Invalid expression term '<'.

If it matters, my browser is IE9.

Upvotes: 1

Views: 132

Answers (1)

Felipe Oriani
Felipe Oriani

Reputation: 38608

The problem is the ForEach is a method that accepts a lambda expression, so, you cannot pass a View (or a piece of html) code in this scope. I recommend you use a simple foreach loop.

@foreach(var field in fields) {
   <label>@field[1]</label>
}

If you have problems with this approach, you also can use the <text> razor tag.

@{

  foreach(var field in fields) {
    <text> 
       <label>@field[1]</label>
    </text>
  }

}

Upvotes: 1

Related Questions