Posted by: Cirilo Meggiolaro | 05/3/2009

Tip of the day #201 – ASP.NET MVC – RadioButton controls

Add radio button controls to your ASP.NET MVC application is pretty straightforward. We are going to use the HtmlHelper that renders a radio button control. The following overloads are available:

  • string RadioButton(this HtmlHelper htmlHelper, string name, object value);
  • string RadioButton(this HtmlHelper htmlHelper, string name, object value, bool isChecked);
  • string RadioButton(this HtmlHelper htmlHelper, string name, object value, IDictionary<string, object> htmlAttributes);
  • string RadioButton(this HtmlHelper htmlHelper, string name, object value, object htmlAttributes);
  • string RadioButton(this HtmlHelper htmlHelper, string name, object value, bool isChecked, IDictionary<string, object> htmlAttributes);
  • string RadioButton(this HtmlHelper htmlHelper, string name, object value, bool isChecked, object htmlAttributes);

How to…

In this example we are going to create a form that gives the user an option to select one city from four cities available.

Creating the controls

The first parameter is a string that determines the name of the control. The name is used not only to identify the control but also to bind values from the ViewData dictionary to the controls. For this particular control, having all with the same name puts them into one logical group. It means that if you check one item so the previous selected, if any, is going to be unselected and so on.

The second parameter is the actual value for the control. That is the value sent to the action method in the controller class when the item is selected.

Other parameters are optional. Feel free to apply as per your needs. Applying the concepts to our city selector example, let’s add four radio buttons to our form and name all of them “radCity” and add a sequential value from 1 to 4 to identify each one of the cities.

<%= Html.RadioButton(“radCity”, “1”) %> New York
<%= Html.RadioButton(“radCity”, “2”) %> Sao Paulo
<%= Html.RadioButton(“radCity”, “3”) %> Toronto
<%= Html.RadioButton(“radCity”, “4”) %> Vancouver

Pre-selecting items

From our action method that loads the page we have an option to pre-select a radio button. Let’s assume we want to pre-select the option Toronto that has value equals 3. The only task you need to perform is to add an entry to the ViewData dictionary (fits better for scenarios where you are not using a strongly-typed View) and name this entry with the same name applied to the radio button controls. The code will be similar to the following:

public ActionResult MyActionMethod()
{
    ViewData["radCity"] = 3;
    return View();
}

For strongly-typed views, make sure to name the controls with the same name of the property that stores the selected value for the city.

Get the selected item during a post

If you are receiving a form collection object during the post you can access the selected value by using the control name.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MyActionMethod(FormCollection form)
{
    int selectedCity = Convert.ToInt32(form["radCity"]);
    return View();
}

The same works if you are accessing the Request object by passing the control name:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MyActionMethod(SomeParameter some)
{
    int selectedCity = Convert.ToInt32(Request["radCity"]);
    return View();
}

If you are working with a strongly-typed form, you may access the property with the same name than the radio button control and you will get the selected city.

About these ads

Responses

  1. Thank you sooo much for this straightforward and well-presented information on how to implement a simple radiobutton in MVC. I spent over a day googling every other site (including MS) and no one else was able to provide the information that you provided. After reading this tip, within 5 minutes I had my radiobuttons saving to the d/b. I wish I would have found your site yesterday morning… I’ll definately have to mark your URL as a favorite…

  2. Hi Chuck,

    Thanks for your comment and visit. I am glad that I could help you.

    Stay tuned!!!!

  3. Cirilo – this is very helpful.

    I need also to trigger the POST when the radiobutton state is changed?

    Is there any way to do so

  4. The RadioButton is rubbish! Though the name should be the same on a RadioButton group, it doesn’t easily let you specify different IDs. That fails validation (minor, though it’ll anoy some people) and it makes it really hard to associate a label to your control (i.e. designs do not always allow you to wrap around your input controls…)

    Saying that though, it’s a good article! This comment should aimed at the haack that came up with it :)

  5. Yo no puedo obtener el elemento seleccionado
    solo no lo hace.

    // [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Test(int preguntaid)
    {
    int Seleccionada = Convert.ToInt32(Request["Respuestas"]);
    return View(PreguntaRespuestas());
    }

    y si dejo la aceptVerbs me manda un error?
    me falta en la vista algo?

  6. It’s really helpful for me, thanks for sharing with us.
    This link is also helpful..

    http://www.mindstick.com/Articles/43165056-d8d9-4cc9-bf5c-2c751d4704df/?RadioButton%20control%20in%20MVC


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: