简体   繁体   中英

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). 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.

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

As a last resort I added FormCollection form to the action parameters and I can see Foo[] actually appearing in the form data.

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. The only time I did this kind of form in the past was when I was working on PHP projects. Naming the checkbox inputs Foo[] was the right way to do this in PHP (I think). Turns out, if I want to do the same in MVC I have to omit the [] and it'll work.

In short for my MVC app my inputs should have looked 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM