The early previews of the MVC Toolkit contained a few helpers that are not available in the current MVC Beta and MVC Beta Futures. On of the ones that was nixed was the CheckBoxList helper. I was in need of this type of functionality lately and found myself out of luck. I needed to add a dynamic list of checkboxes to a form, like the roles that a user could possible be a member of. These roles could be added to or deleted from at any time.
I looked to the Html.CheckBox helper to see if that would work. This helper can be used like so:
The problem with using Html.CheckBox for my scenario arises when you need to get the values in the form ActionMethod. For Html.CheckBox, the form handler is expecting a boolean parameter for each checkbox. An example is show below.
As you can see, this would not satisfy the requirements that I had. So what is the answer? Create my own CheckBoxList helper of course.
Here is the extension method code for my implementation, along with a simple class that contains the info needed for each checkbox in the list..
This can then be used to render the list of checkboxes in a View as shown below:
And now, in the post ActionMethod, we can access the ones that have been checked like so:
In addition to solving the issue that I was having, this post shows how easy it is to implement your own custom helpers in MVC.