After the last post on how to create check boxes that use the bootstrap “btn-group” to modify the look and feel of check boxes, I thought it would be good to show how to bind these check boxes using MVC. After all, you will most likely need to display check boxes based on data from a table.
Figure 1: Check boxes should be bound to an entity class
Musical Tastes Entity Class
The first step is to have an entity (or model) class that contains the appropriate properties to bind to these check boxes. Below is a class I called MusicalTastes that simply has three Boolean properties that correspond to the three check boxes on the screen shown in Figure 1.
View for Musical Tastes
Create a .cshtml view and add a @model statement at the top of the page to bind to an instance of this MusicalTastes class. Use the @Html.CheckBoxFor() helper to bind to each property instead of the @Html.CheckBox() helper as you did in the last blog entry.
Notice that the expressions you pass to the first parameter of this CheckBoxFor helper have the names of each of the properties in the MusicalTastes class. This is what binds this check box to each of the properties.
Binding to Musical Tastes
In the controller for this .cshtml page create an instance of the MusicalTastes class and set one or more of the properties to true in order to see the check box checked when the page displays.
jQuery for Musical Tastes
This code selects all check boxes checked via the automatic data binding. It then removes the unchecked glyph and adds the ok-circle glyph to all those check boxes.
Posting Back Musical Tastes Selected
There is nothing to do to get the selected check boxes to post back to your entity class. Simply create a method in your controller with the [HttpPost] attribute. Pass in the entity class to this method and MVC will take care of matching the names of the check boxes to the appropriate properties in your entity class.
I added the Debugger.Break() statement so I can hover over the ‘entity’ variable and verify that the check boxes checked have been updated in the instance of the MusicalTastes class passed in.