Search code examples
formsrazormodel-view-controllerforeachhtml.beginform

Html.BeginForm not outputting Form for first item in collection


I am using MVC5 and want to display a form for each item in a collection. The form will post to an action in a different controller when submitted.

My razor is as follows:

@foreach (var skuInOrder in Model.Order.Skus)
{
    using (Html.BeginForm("Delete", "SkuInOrders", new { id = skuInOrder.Id }, FormMethod.Post, new { name = skuInOrder.Id, id = skuInOrder.Id }))
    {
        <input id="orderId" name="orderId" value="Model.Order.Id" type="hidden" />
        <input type="submit" class="btn btn-default" value="Delete" />
    }
}

This code works for all items in the collection apart from the first one.

For the second item onwards, the form element is displayed and works as expected, but the form is not outputted for the first item. Instead I simply get the two elements not within a element.

This is an example of the outputted HTML (with 2 items in the collection) via Firefox Dev tools. Notice that there is no form for the first item and the inputs are displayed on their own, but there is a form for the second item.

I cannot post images as I do not have enough rep but you can download it form here: https://onedrive.live.com/redir?resid=999be3b43db18398%211133026

Update I have now discovered that I get this behaviour even with a standard HTML form (not just @Html.beginForm). For example, this razor code also removes the form elements for the first item but not for subsequent ones.

<form action="/SkuInOrders/Delete/@skuInOrder.Id" method="post" >
    <input id="orderId" name="orderId" value="@Model.Order.Id" type="hidden" />
    <input type="submit" class="btn btn-default" value="Delete" />
</form>

Solution

  • This is now resolved ... it was because I had nested Forms (the whole page was an edit page so was wrapped in a form).

    This SO question explains it: form tag dissapear in foreach loop razor MVC 3