views:

424

answers:

3

I'm using a FormCollection to get client input on an ASP.Net MVC view. I was using a checkbox, and I would just check to see if the FormCollection's AllKeys list contained the name of the checkbox I was checking. I now need to switch to a radio button, but since the inputs need to have the same name (which seems a bit silly to me), I can't determine which radio button was selected.

Or can I?

+3  A: 

Well if you have three radio buttons all with the same name, then when you get the values back in the form collection, the value of that key will be the value of the selected radio button. That is how they work. They use the same name as a logical grouping so selecting one, deselects the previous. So you can assume that the value is the value of the selected radio button if you identify the group by name!

Andrew

REA_ANDREW
If I have the following: <input type="radio" name="test" value="Value A" /> <input type="radio" name="test" value="Value B" /> <input type="radio" name="test" value="Value C" />And I check the third radio button, the FormCollection only has one key, the string "test". "Value C" is no where to be found. Am I missing something?
Mike Pateras
That is correct. Out of three radio buttons you can only expect one key being the name, and the value of that selected one. Value C for a start is the value and not the key. Check in the values collection and you will see it in there. Not the keys collection
REA_ANDREW
Ah, I didn't know I could access the value of the input through the FormCollection object. The GetValue() method was what I needed. Thanks!
Mike Pateras
A: 

I used jQuery for this one and set a hidden field.

So I have something like this;

var RadioButtonValue = $('input:radio[class=RadButtonClassGroupName]:checked').val();

I can then set the hidden field value to be the RadioButtonValue.

I know this solution kinda sucks for you but I used it like this in a jQuery ajax post back but if all else fails can be applied to your problem as well.

griegs
The default model binding is designed for this. Simply submit a form with ajax and intercept the form submit event, stop it and then do what you need to do. I find this a much more elegant solution. As you are still preserving the core html form data passing and you are enabling ajax posts
REA_ANDREW
I should have mentioned that were using WebForms and not the MVC Framework.
griegs
+1  A: 

Assuming that you have 3 radiobuttons like this:

 <% = Html.RadioButton("radio", "1")%>
 <% = Html.RadioButton("radio", "2")%>
 <% = Html.RadioButton("radio", "3")%>

When you POST, you will get just 1 value, the one checked, like this:

var radio = Convert.ToInt16(Request.Form["radio"]);

The formCollection will contain just one key with the respective value.

I encourage you to use the model binders either by direct parameter binding:

public ActionResult Action(int radio)

or using a ViewModel.

Omar