Dave Dave - 3 months ago 8
C# Question

Dynamically add buttons based on count in for loop

I want to add button with unique different id in for loop.
Like

<input id=1 type="submit" value="Remove" />
<input id=2 type="submit" value="Remove" />
<input id=3 type="submit" value="Remove" />


And so on

@{

using (Html.BeginForm("Action", "Controller"))
{
for (int i = 0; i< 3; i++)
{
@Html.TextBoxFor(m => m[i].Title)
<input id={i} type="submit" value="Remove" />
}

<input type="submit" value="Submit" />
}
}

Answer

You can do this:

@{

using (Html.BeginForm("Action", "Controller"))
{
    for (int i = 0; i< 3; i++)
    {
        @Html.TextBoxFor(m => m[i].Title)
        <input id="@i" type="submit" value="Remove" />
    }

    <input type="submit" value="Submit" />
  }
}