MVC Checkbox and Bootstrap

Bootstrap v3 has some very nice implementations of boolean selectors. You can read the documentation here – http://getbootstrap.com/javascript/#buttons.

I have modified the default functionality to incorporate some formatting. More importantly, I have a small block of javascript that will make MVC integration much easier. It’s also generic enough to have in a global javascript file which you can apply across your entire site.

Here are the details. Firstly, let’s look at the HTML in the MVC view. This block includes some Razor code and relates to a model field called checkboxField. This is a BIT field in the database and it does not allow nulls.

<div class="form-group">
	<label class="col-md-3" for="checkboxField">Checkbox Label</label>
	<div class="col-md-9">
		<!-- bootstrap button group -->
		<div class="btn-group btn-toggle-radio" data-toggle="buttons-radio">
			<button type="button" data-model-field="checkboxField" class="btn btn-default" id="buttonFilterYes">Yes</button>
			<button type="button" data-model-field="checkboxField" class="btn btn-success active" id="buttonFilterNo">No</button>
		</div>
		<!-- MVC razor code -->
		@Html.CheckBoxFor(model => model.checkboxField)
		@Html.ValidationMessageFor(model => model.checkboxField)
	</div>
</div>

That’s all you need to do. The association is made between the data-model-field and the actual model field name. They must be the same for the javascript to work. Here is the javascript.

$(".btn-toggle-radio button").click(function () {
	//  do the Bootstrap formatting
	$(this).siblings().removeClass("active btn-success");
	$(this).siblings().addClass("btn-default");
	$(this).removeClass("btn-default");
	$(this).addClass("active btn-success");

	//  get the data attribute that matches the model field name
	var checkboxToUpdate = $(this).attr("data-model-field");
	//  did the user click YES or NO?
	if ($(this).attr("id") == "buttonFilterYes") {
		$("#" + checkboxToUpdate).prop("checked", true);
	} else {
		$("#" + checkboxToUpdate).prop("checked", false);
	}
});

That’s it. Pretty simple, and yet very effective.

Til next time ..


Leave a Reply

Your email address will not be published. Required fields are marked *