[英]How to make post action accept array parameters?
I have a form in which there is a bunch of dynamically generated checkboxes. 我有一个表格,其中有一堆动态生成的复选框。 Something like this: 像这样:
<input type="checkbox" name="Foo[]" value="1"/> Bar
<input type="checkbox" name="Foo[]" value="2"/> Baz
<input type="checkbox" name="Foo[]" value="2"/> Bay
I had a int[] Foo
property in my model and I expected it to be filled with the data from those checkboxes, but it's value is always null (regardless of whether I check any of the checkboxes or not). 我的模型中有一个int[] Foo
属性,我希望它会被这些复选框中的数据填充,但是它的值始终为null(无论是否选中任何复选框)。 Since this failed I just added int[] Foo
as a plain old parameter to the action just to make is it wasn't something caused by the model, but Foo
was still null. 因为失败了,所以我只是将int[] Foo
作为普通的旧参数添加到操作中,只是因为这不是由模型引起的,但是Foo
仍然为空。
I checked what browser has to say about my post, but the values from the checkboxes are there (if I check them of course). 我检查了浏览器对我的帖子要说些什么,但是复选框中的值在那里(如果我当然选中的话)。
Foo[] = 1 Foo[] = 2 Foo[] = 3 Foo [] = 1 Foo [] = 2 Foo [] = 3
As a last resort I added FormCollection form
to the action parameters and I can see Foo[]
actually appearing in the form data. 作为最后的选择,我将FormCollection form
添加到动作参数中,并且可以看到Foo[]
实际上出现在表单数据中。
So waht am I doing wrong here? 那么我在这里做错了吗? How to make an action accept an array query parameter? 如何使一个动作接受数组查询参数?
I got enlightened (while taking a break to make some tea). 我得到了启发(休息片刻时喝了些茶)。 The fact that in the FormCollection form
the parameter was called Foo[]
rather than just Foo
lead my to the source of the problem. 在FormCollection form
该参数称为Foo[]
而不是Foo
的事实导致了问题的根源。 The only time I did this kind of form in the past was when I was working on PHP projects. 过去,我唯一的一次做这种表格是在我从事PHP项目时。 Naming the checkbox inputs Foo[]
was the right way to do this in PHP (I think). 命名复选框输入Foo[]
是在PHP中执行此操作的正确方法(我认为)。 Turns out, if I want to do the same in MVC I have to omit the []
and it'll work. 事实证明,如果我想在MVC中做同样的事情,我必须省略[]
,它将起作用。
In short for my MVC app my inputs should have looked like this: 简而言之,对于我的MVC应用程序,我的输入应如下所示:
<input type="checkbox" name="Foo" value="1"/> Bar
<input type="checkbox" name="Foo" value="2"/> Baz
<input type="checkbox" name="Foo" value="2"/> Bay
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.