Search code examples
asp.netasp.net-mvcvisual-studiomodel-view-controllere-commerce

In this For loop count is not increasing


            <tbody>
                @foreach (var item in Model)
                {
                    int count = 1;
                    <tr>
                        <td>@count</td>
                        <td>@item.ProductName</td>
                        <td>

                            @Html.ActionLink("Edit", "ProductEdit", new { productId = item.ProductId })
                        </td>

                    </tr>
                    count = count + 1;
                }

            </tbody>

This code is to display the products in a table with serial number as count but the count is not increasing


Solution

  • You need to initialize the variable outside of the for loop, or it will not increase:

    <tbody>
    @{
        int count = 1;
        foreach (var item in Model)
        {                
            <tr>
                <td>@count</td>
                <td>@item.ProductName</td>
                <td>
                    @Html.ActionLink("Edit", "ProductEdit", new { productId = item.ProductId })
                </td>
    
            </tr>
            count = count + 1;
        }
    }
    </tbody>