Search code examples
asp.net-mvchtml.actionlink

How do I use a @Html.ActionLink inside a for loop


How can I pass a value of PGId to controller by use a for loop. I want to only use for loop in my case

When I use a for loop It's not work fine:

            for (int i = 0; i < Model.Count; i++)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(m => m[i].PGId)
                        @Html.HiddenFor(m => m[i].PGId)
                    </td>
                    <td>
                        @Html.ActionLink("Edit", "Edit", // pass PGId from here ???)
                    </td>
                </tr>
            }

When I use a foreach loop my code work fine

                foreach (var item in Model)
                {
                    <tr>
                        <td>
                            @Html.DisplayFor(modelItem => item.PGId)
                        </td>
                        <td>
                            @Html.ActionLink("Edit", "Edit", new { id = item.PGId})
                        </td>
                    </tr>
                }

Solution

  • Use Model[i]:

    for (int i = 0; i < Model.Count; i++)
    {
        <tr>
            ...
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = Model[i].PGId })
            </td>
        </tr>
    }