一个MVC表单上的多个表单,用循环创建,只有第一个提交数据 [英] Multiple forms on one MVC form, created with a loop, only the first submits data

查看:20
本文介绍了一个MVC表单上的多个表单,用循环创建,只有第一个提交数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的代码,只有第一个表单提交任何东西,下面提交空值,每个模型都有数据.如果我将其更改为一个大表单,则所有内容都会提交.为什么其他单个表单发布空值?

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?

查看

@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>

控制器

[HttpPost]
public ActionResult controllerAction(myModel[] models)
{
    ...do stuff...
}

推荐答案

原因是你在 for 循环中使用索引器创建表单控件,并且你的 POST 方法参数是 myModel[] 模型.

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

默认情况下,DefaultModelBinder 要求集合从零开始并且是连续的,因此如果您尝试提交第二个表单,则回发 [1].property1: someValue 等.因为索引器从 1 开始,绑定失败,模型为 null.

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.

您可以通过为模型绑定器用于匹配非连续索引器的 Index 属性添加隐藏输入来解决此问题

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>

这篇关于一个MVC表单上的多个表单,用循环创建,只有第一个提交数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆