Notice: Trying to get property 'display_name' of non-object in /home/woolsto1/webdesignwith.net/wp-content/plugins/wordpress-seo/src/generators/schema/article.php on line 52

MVC Razor Boolean EditorTemplate With Bootstrap Formatting (Updated)

In my post - MVC Razor Boolean Formatting - I talked about using Editor Templates to globally use Bootstrap boolean controls in your MVC application. With the Bootstrap v3 release, that code has become obsolete. So, in the interests of correctness, I thought it necessary to show updated code.

@model bool?

    @{
        // make use of MVC4 nullable class attribute values
        var yesSelected = Model.HasValue && Model.Value ? "active btn-success" : null ;
        var noSelected = Model.HasValue && !Model.Value ? "active btn-success" : null;
        var noSelection = !Model.HasValue ? "active" : null;   
    
        // get the name of the ID - this is to support multiple fields     
        var htmlField = ViewData.TemplateInfo.HtmlFieldPrefix;
    }

    @Html.HiddenFor(model => model)

    <div class="btn-group btn-group-@htmlField">
        <button type="button" class="btn btn-default @yesSelected bool-@htmlField" 
            onclick="javascript:$('.btn-group-@htmlField button.active').removeClass('active btn-success');$('#@htmlField').val(true);$(this).addClass('active btn-success');">Yes</button>
        <button type="button" class="btn btn-default @noSelected bool-@htmlField" 
            onclick="javascript:$('.btn-group-@htmlField button.active').removeClass('active btn-success');$('#@htmlField').val(false);$(this).addClass('active btn-success');">No</button>
    
        @if (ViewData.ModelMetadata.IsNullableValueType)
            { <button type="button" class="btn btn-info @noSelection bool-@htmlField" onclick="javascript:$('#@htmlField').val('');" >Do Not Set</button> }

    </div>

Til next time...