0

I have a foreach loop in my ASP.NET code and I am trying to add a counter by adding @counter++ at the end of the loop, but it's not working, I get an invalid expression term error. I have also tried @{ counter++ } but that didn't work either.

<table border="1" style="width:762px;height:25px; border-style:1px solid #000; border-collapse:collapse; clear:both;">
@{
    int counter = 1;
}
@foreach (var person in @ViewBag.POLoopList)
{
    <tr>
        <td style="width:24px; text-align:right;">@counter</td>
        <td style="width:55px">@person.EstPhase</td>
        <td style="width:32px">@person.JCCategory</td>
        <td style="width:180px">@person.ItemsDesc</td>
        <td style="width:90px; text-align:left;">@person.Comments</td>
        <td style="width:57px; text-align:right;">@person.OrderQty</td>
        <td style="width:40px; text-align:center;">@person.OrderUOM</td>
        <td style="width:56px; text-align:right;">@Convert.ToDouble(person.Rate).ToString("N")</td>
        <td style="width:70px; text-align:right;">[email protected](person.Pretax).ToString("N")</td>
    </tr>
    @counter++
}
</table>
1

2 Answers 2

3

Remove the @ from @counter++:

<table border="1" style="width:762px;height:25px; border-style:1px solid #000; border-collapse:collapse; clear:both;">
            @{
                int counter = 1;
            }
            @foreach (var person in @ViewBag.POLoopList)
            {
                <tr>
                    <td style="width:24px; text-align:right;">@counter</td>
                    <td style="width:55px">@person.EstPhase</td>
                    <td style="width:32px">@person.JCCategory</td>
                    <td style="width:180px">@person.ItemsDesc</td>
                    <td style="width:90px; text-align:left;">@person.Comments</td>
                    <td style="width:57px; text-align:right;">@person.OrderQty</td>
                    <td style="width:40px; text-align:center;">@person.OrderUOM</td>
                    <td style="width:56px; text-align:right;">@Convert.ToDouble(person.Rate).ToString("N")</td>
                    <td style="width:70px; text-align:right;">[email protected](person.Pretax).ToString("N")</td>
                </tr>
            counter++
            }
        </table>
Sign up to request clarification or add additional context in comments.

Comments

2

When inside of a foreach and you have not placed the variable within an html element, you do not need the @ symbol.

change:

@counter++

to

counter++

Additionally, here is a nice quick guide on Razor Syntax

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.