Consider the following code which has a CheckBox and a submit button:

Submit the form. The request body has the form data with name-value pairs. If the user checks the checkbox, the form data has Select=on. If the user clears the checkbox, the form data does not contain Select.

All of the form data is bound to a model. A typical action method has a Select parameter.

The checkbox may have a value attribute. This value is sent to the server as part of form data.

HtmlHelper

As an alternative to plain HTML, MVC has HTML helpers.

The Checkbox HtmlHelper has a limitation. It sends only true or false in the form data. The markup produced by the helper is:

It has one advantage. Even when there is no selection, the form data has a value of false. 

Sometimes, we need a list of checkboxes with unique values assigned to each of them.

For such a collection, the form data has an array of values. The action method will have the following signature.

The above logic is not possible with the CheckBox HtmlHelper that comes out as default in MVC.

ValuedCheckBox

We create our own HtmlHelper extension method.

The ValuedCheckBox extension method produces a simple HTML markup. Use it as follows.

ValuedCheckBox is useful to display checkboxes in a grid.

CheckBox Helper in MVC
Tagged on: