Gtopuria Gtopuria - 3 months ago 21
ASP.NET (C#) Question

using keyword inside foreach ASP MVC

Inside my view I need to use a form on every iteration, but if I put

@using
inside
foreach
it isn't working,

@foreach (var item in list)
{
<tr>
<td>@Html.DisplayName(item.name)</td>

@using(Html.BeginForm("Index", "Home", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
<td>@Html.TextBoxFor(model=> model.quantity, new { @class = "form-control" })</td>

<td>@Html.DropDownList("idid", (IEnumerable<SelectListItem>)ViewData["list"], "Select ...", new { @class = "form-control" })</td>
<td>@Html.DisplayFor(model=> model.id, new { Value = item.id })</td>
<td><input type="submit" class="btn btn-default" value="Send" /></td>


}
</tr>
}

Answer

Your HTML is not well formed, and I suspect that is the reason you are getting the error. When your form element is created, it will contain <td> elements, not a complete table. When it is generated, it will look like this.

<table>
    <tr>
        <td></td>
        <form>
            <td></td>
            <td></td>
            <td></td>
        </form>
    </tr>
</table>

You must put the form inside of the <td> elements or outside of the <table> element for it to produce valid HTML.

<form>
    <table>
        <tr>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
    </table>
</form>

Or

<table>
    <tr>
        <td><form><!-- input and other html elements here --></form></td>
        <td><form><!-- input and other html elements here --></form></td>
        <td><form><!-- input and other html elements here --></form></td>
        <td><form><!-- input and other html elements here --></form></td>
    </tr>
</table>
Comments