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?

2
  • 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)) Commented Nov 21, 2014 at 15:07
  • possible duplicate of Unexpected "foreach" keyword after "@" character Commented Nov 21, 2014 at 15:16

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.