1 MVC形式多种形式,用循环创建,只有第一个提交数据 [英] Multiple forms on one MVC form, created with a loop, only the first submits data
问题描述
我有以下的code,只有第一个表单提交什么,下面提交空值,每个模型都有数据。如果我改变它只是一个大的形式,一切提交。为什么其他个人形式发布NULL值?
查看
@model基于myModel []
< UL>
@for(INT I = 0; I< Model.Length;我++)
{
使用(Html.BeginForm(controllerAction,控制器,FormMethod.Post,
新{ID =形+ I}))
{
<立GT;
@ Html.TextBoxFor(一个=>一种由[i] .property1)
@ Html.CheckBoxFor(一个=>一种由[i] .property2)
@ Html.HiddenFor(一个=>一种由[i] .property3)
<输入类型=提交/>
< /李>
}
}
< / UL>
控制器
[HttpPost]
公众的ActionResult controllerAction(基于myModel []型号)
{
...做东西...
}
的原因是你创建窗体控件在你的为
循环索引,和你的POST方法参数为基于myModel []车型
。
默认情况下, DefaultModelBinder
需要收集是零基础,连续的,所以如果你尝试提交第二表单,您的回发 [ 1] .property1:someValue中
等等。因为索引从1开始,绑定失败,该模型是空
您可以通过添加一个隐藏的输入通过模型绑定使用的首页
属性相匹配的非连续索引解决这个
<立GT;
@ Html.TextBoxFor(一个=>一种由[i] .property1)
@ Html.CheckBoxFor(一个=>一种由[i] .property2)
@ Html.HiddenFor(一个=>一种由[i] .property3)
<输入类型=隐藏的名字=索引值=@我/> //添加此
<输入类型=提交/>
< /李>
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...
}
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>
这篇关于1 MVC形式多种形式,用循环创建,只有第一个提交数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!