2

I am having a hard time understanding why this won't work:

@if ((Model.doaFormGroupDocuments.Count != 0) || (Model.doaFormGroupDocuments != null))
{
    @for(var i = 0; i < Model.doaFormGroupDocuments.Count; i++)
    {
        @Html.HiddenFor(model => model.doaFormGroupDocuments[i].Checked)
        @Html.HiddenFor(model => model.doaFormGroupDocuments[i].Id)
        @Html.HiddenFor(model => model.doaFormGroupDocuments[i].Name)
    }
}

I am getting a red error line under the @ next to the for loop. Is this not allowed in HTML?

Sam Greenhalgh
  • 5,952
  • 21
  • 37
John
  • 265
  • 2
  • 5
  • 16
  • 3
    Side note: You may run into an error there, `.Count` won't be available if `doaFormGroupDocuments == null`, so the order of the comparisons in the if statement should be reversed to this (and it should be `&&` not `||`): `if ((Model.doaFormGroupDocuments != null) && (Model.doaFormGroupDocuments.Count != 0))` – entropic Nov 21 '14 at 15:07
  • possible duplicate of [Unexpected "foreach" keyword after "@" character](http://stackoverflow.com/questions/4946334/unexpected-foreach-keyword-after-character) – Alexei Levenkov Nov 21 '14 at 15:16

2 Answers2

3

John, This looks like ASP.NET MVC, I'm going to assume that's the case.

What happens is you have two contexts, HTML and Razor, any time you have an @ it switches to the Razor context, when you have an HTML tag, <text> or @: it switches the HTML context.

Visual Studio is complaining because you are in the razor context (from your if statement), and trying to go into the razor context again with the @for, you just need to remove the @ before the for loop. Also as a note, the three helper calls inside your for loop will be handled correctly because it knows that you're returning IHtmlStrings there.

Shriike
  • 1,351
  • 9
  • 20
1

You are already inside a code block in your razor so you don't need the @ preceding the for keyword.

@if ((Model.doaFormGroupDocuments.Count != 0) || (Model.doaFormGroupDocuments != null))
{
    for(var i = 0; i < Model.doaFormGroupDocuments.Count; i++)
    {
        @Html.HiddenFor(model => model.doaFormGroupDocuments[i].Checked)
        @Html.HiddenFor(model => model.doaFormGroupDocuments[i].Id)
        @Html.HiddenFor(model => model.doaFormGroupDocuments[i].Name)
    }
}

See this question

Unexpected "foreach" keyword after "@" character

Community
  • 1
  • 1
Sam Greenhalgh
  • 5,952
  • 21
  • 37