ASP.NET MVC Free Tool: CheckBoxList(For)
Courtesy Peter Vogel, VisualStudioMagazine
ASP.NET MVC’s HtmlHelp has a TextBoxFor, a DropDownListFor, and even a HiddenFor method…but it doesn’t have a CheckBoxListFor method. CheckBoxList(For) by Mikhail Tsennykh fills that gap and makes it easy to generate a list of checkboxes for an array of objects to let users can select which objects they want.
There are 16 overloads for Mikhail’s CheckBoxList method, but the simplest version requires just five parameters:
- The text to use for the select tag’s name and id attributes
- The list of objects to generate checkboxes for (you’ll get one checkbox for each object)
- The property whose value is returned to the server when the user selects that checkbox
- The property whose value is displayed beside the checkbox in the page
- The list of objects that should be shown as already checked
If you don’t have any already selected items, you can get away with just the first four parameters.
Here’s an example that displays a list of User objects, returns the User object’s ID property to the controller, displays the User’s name property beside the checkbox, and checks off those User objects that also appear in the collection called AlreadySelectedUsers:
@Html.CheckBoxList("Users", Function(m) m.Users, Function(u) u.ID, Function(u) u.Name, Function(m) m.AlreadySelectedUsers)
It’s easy to switch between a horizontal or vertical list of checkboxes (the control even supports right-to-left reading order) and you can add on as many additional HTML attributes as you need.
At the controller, you’ll get back a string array of the second parameter—one for each object whose checkbox the user checked in the browser. The controller method that would accept my sample CheckBoxList would look like this:
Function Change(usrDTO As UserDTO, Users As String())
You can install CheckBoxList(For) through NuGet or download it from CodeProject (where you’ll also find some documentation on how to use the extension and a sample application showing it in action). The method even attaches itself to the HtmlHelp control, where it belongs.