views:

913

answers:

2

Hi,

I tried to follow this but the default modelbinder let my array null on the server side.

HTML:

Question 1:
<input name="list[0]" type="radio" value="1000" />No
<input name="list[0]" type="radio" value="1001" />Yes
Question 2:
<input name="list[1]" type="radio" value="1002" />No
...

Controller action:

 public ActionResult Anamnesis(string[] list)
 {

If I choose only the second "No" (list[0] is missing) then the DefaultModelBinder is impossible to transform it into an array.

Thanx in advance!

Update#1

Reformatted based on the comment, thank you!

Update#2

Just a tought: created a hidden input after all list item, and in this way it works. But it's ugly, no doubt.

Question 1:
<input name="list[0]" type="radio" value="1000" />No
<input name="list[0]" type="radio" value="1001" />Yes   
<input type="hidden" name="list[0]"/>
Question 2:
<input name="list[1]" type="radio" value="1002" />No
<input type="hidden" name="list[1]"/>
...

Order it's very important: the hidden value submits only when the radio is unchecked. The idea it's from the ASP.NET MVC helpers. (Btw I cannot use Html.RadioButton to archive this behavior.)

A: 

The name attribute of the radio button should be list, not list[n].

eulerfx
This is a list of possible answers for question. First question's answers are list[0], second question's answers list[1] etc. If I write just "list" instead of indexing it, the user can select ony one answer _per_ page.
boj
then use a checkbox
eulerfx
A: 

Your Update #2 seems like it solves your problem. Your Update #2 is also interesting in that you could also use this approach to supply a default value (such as 999) to be used whenever nothing is checked.

There is perhaps another similar way to do what you are asking, which is based on this article and which also uses hidden inputs. The idea is that you can create indexes for each of your radio sets, to avoid the situation where a missing selection earlier in the form causes all subsequent selections to be dropped:

Question 1:
<input name="list.Index" type="hidden" value="0" />
<input name="list[0]" type="radio" value="1000" />No
<input name="list[0]" type="radio" value="1001" />Yes
Question 2:
<input name="list.Index" type="hidden" value="1" />
<input name="list[1]" type="radio" value="1000" />No
<input name="list[1]" type="radio" value="1001" />Yes

The reason I suggest this, is in the case where you might like to associate your answers with a specific question by a unique ID, instead of just using 0, 1, 2 etc. The article I linked will show an example of how to do this.

Good luck!
-Mike

Funka
Cleaner solution then mine, thanx!
boj