开发者

ASP.Net MVC: Can I use a FormCollection to determine which radio button was selected?

I'm using 开发者_如何学Goa 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?


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜