MVC Razor Boolean EditorTemplate With Bootstrap Formatting

EDITOR NOTE: This approach is obsolete since the release of Bootstrap v3. See this post for more details.

The bootstrap btn-group “toggle” functionality is quite nice and very intuitive. Here is an EditorTemplate for MVC that will format all boolean model fields as Bootstrap button groups.

@model bool?
@{
	Dictionary<string, object> yesAttrs = new Dictionary<string, object>();
	Dictionary<string, object> noAttrs = new Dictionary<string, object>();

	yesAttrs.Add("id", ViewData.TemplateInfo.GetFullHtmlFieldId("") + "Yes");
	noAttrs.Add("id", ViewData.TemplateInfo.GetFullHtmlFieldId("") + "No");
	var yesClass = "";
	var noClass = "";

	if (Model.HasValue && Model.Value)
	{
		yesAttrs.Add("checked", "checked");
		yesClass = "active";
	}
	else if (Model.HasValue && !Model.Value)
	{
		noAttrs.Add("checked", "checked");
		noClass = "active";
	}
}

<div class="btn-group" data-toggle="buttons">
	<label class="btn btn-primary @yesClass">
		@Html.RadioButtonFor(x => x, "true", yesAttrs)
		<label for="@(ViewData.TemplateInfo.GetFullHtmlFieldId(""))Yes">Yes</label>
	</label>
	<label class="btn btn-primary @noClass">
		@Html.RadioButtonFor(x => x, "false", noAttrs)
		<label for="@(ViewData.TemplateInfo.GetFullHtmlFieldId(""))No">No</label>
	</label>
</div>

6 Comments

1 Trackback

Leave a Reply

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