Wednesday, April 07, 2010

A strongly typed RadioButtonList for ASP.NET MVC

There are many strongly typed controls in ASP.NET MVC. For example TextBoxFor. I really like using the strongly typed HTML helpers because you get much better information at compile time. Especially if you've turned on compile time view checking.

The one control that was missing, however is RadioButtonList. There is no "RadioButtonListFor" to be found. So I wrote my own.

This is what the code looks like in the aspx
<%= Html.RadioButtonListFor(m => m.GenderRadioButtonList)%>

Here's the code in the controller to check what the user has selected

public ActionResult Submit(HomePageViewModel viewModel)
{
  if (viewModel.GenderRadioButtonList.SelectedValue == HomePageViewModel.GenderType.Female)
  {
    // Do something
  }
  return View("Index", viewModel);
}
The code, plus a sample website using it, is in this zip file.

Additionally, at the risk of creating an infinite loop, here's a StackOverflow question that this post is an answer to. It's got some useful comments and more code.

10 comments:

Anonymous said...

Your zip file link appears to be broken.

Glen McGregor said...

What problem are you having? It works fine for me.

Anonymous said...

Will validation attributes and filters work with your RadioButtonListFor helper?

Glen McGregor said...

I haven't tried validation attributes but I don't see why they wouldn't work.

Mike said...

I am getting


Error 1 The name 'RadioButtonListFor' does not exist in the current context

Have you any idea what I am doing wrong ?

HtmlHelperExtensions.cs is my project but does not seem to get picked

Glen McGregor said...

@mike do you have a using statement for the nakedness you put HtmlHelperExtensioms in?

Glen McGregor said...

In my comment above 'nakedness' should read 'namespace'... stupid autocorrect

.NET Development said...

Very good written article. It will be useful to everyone who employess it, including myself. Keep up the good work – can’r wait to read more posts.

Utkarsh said...

Sir,I am new to ASP.NET MVC3,i was confused how to use the files when i unzipped.Is it that i just have to include the HtmlHelperExtension.cs class in my model class?n that would do the work for me?

Glen McGregor said...

@Utkarsh, if you have a look at the linked StackOverflow answer (http://stackoverflow.com/a/2590001/173467) it's got more detailed information on what code goes where.