Reputation: 7007
I need to receive and unknown number of Radio Buttons values on my controller.
The radio buttons are generated and may vary... So i need a way to receive as many as the user send. How can i achieve this?
View (using Velocity):
...
#foreach( $f in $model.fields )
<input type="radio" name="rd_$f.name" value="S" checked="checked"/> S
<input type="radio" name="rd_$f.name" value="C" /> C
#end
...
This will generate X number of radio buttons sets... I Need to receive it on my controller:
@RequestMapping(value = "/{e}/{id1}/{id2}", method = RequestMethod.POST)
public ModelAndView salvar(@PathVariable(value = "e") String e,
@PathVariable(value = "id1") Long id1,
@PathVariable(value = "id2") Long id2,
//MY RADIO BUTTONS ARRAY HERE!
) {
...
}
UPDATE:
The html generated is something like:
...
<input type="radio" name="rd_1" value="S" checked="checked"/> S
<input type="radio" name="rd_1" value="C" /> C
...
<input type="radio" name="rd_2" value="S" checked="checked"/> S
<input type="radio" name="rd_2" value="C" /> C
...
<input type="radio" name="rd_n" value="S" checked="checked"/> S
<input type="radio" name="rd_n" value="C" /> C
...
So i can't just bind to a [] on the controller, right?
Upvotes: 2
Views: 8922
Reputation: 17472
You can bind using @RequestParam(value="radio_name") String[] radioCheckedValues
as one more attribute in your spring controller.
EDIT
The only way a server can know about what's coming from the client is using the name. You can use the request.getParameterNames
.
Pseudo code...
List<String> values = new ArrayList();
Enumeration<String> enumeration = req.getParameterNames();
while (enumeration.hasMoreElements()) {
String parameterName = (String) enumeration.nextElement();
if(parameterName.startsWith("rd_")) {
values.add(req.getParameter(parameterName));
}
}
Upvotes: 4
Reputation: 6226
Use []
in the name to group each radiobox in one array:
#foreach( $f in $model.fields )
<input type="radio" name="radio[]" value="S" checked="checked"/> S
<input type="radio" name="radio[]" value="C" /> C
#end
Then read this array in the controller.
Edit:
To retrieve values use (loop on each array):
String[] params = request.getParameterValues("rd_n");
Upvotes: 1