Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
765 views
in Technique[技术] by (71.8m points)

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

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 submits. Why do the other individual forms post null values?

View

@model myModel[]
<ul>
    @for (int i = 0; i < Model.Length; i++)
    {
        using (Html.BeginForm("controllerAction", "Controller", FormMethod.Post,
                               new { id="Form"+i }))
        {
            <li>
                @Html.TextBoxFor(a => a[i].property1)
                @Html.CheckBoxFor(a => a[i].property2)
                @Html.HiddenFor(a => a[i].property3)
                <input type="submit" />
            </li>
        }
    }
</ul>

Controller

[HttpPost]
public ActionResult controllerAction(myModel[] models)
{
    ...do stuff...
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

<li>
    @Html.TextBoxFor(a => a[i].property1)
    @Html.CheckBoxFor(a => a[i].property2)
    @Html.HiddenFor(a => a[i].property3)
    <input type="hidden" name="Index" value="@i" /> // add this
    <input type="submit" />
</li>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...