Multiple forms on one MVC form, created with a loop, only the first submits data

后端 未结 1 830
灰色年华
灰色年华 2020-12-19 20:13

I have the following code, only the first form submits anything, the following submit null values, each model has data. If I change it to just one large form, everything sub

1条回答
  •  孤城傲影
    2020-12-19 20:50

    The reason is that your creating form controls with indexers in your for loop, and your POST method parameter is myModel[] models.

    By default, the DefaultModelBinder requires collection to be zero based and consecutive, so if you attempt to submit the second form, your posting back [1].property1: someValue etc. Because the indexer starts at 1, binding fails and the model is null.

    You can solve this by adding a hidden input for an Index property used by the model binder to match up non consecutive indexers

  • @Html.TextBoxFor(a => a[i].property1) @Html.CheckBoxFor(a => a[i].property2) @Html.HiddenFor(a => a[i].property3) // add this
  • 0 讨论(0)
提交回复
热议问题