Search code examples
twitter-bootstrapbootstrap-4asp.net-core-mvcmodel-bindingasp.net-core-tag-helpers

How to bind MVC .net core checkbox with label as button


I have the following code which creates a checkbox that looks like a toggle button.

<div class="btn-group btn-group-toggle" data-toggle="buttons">
 <label asp-for="FlaggedStatus" class="btn btn-outline-danger">
   <input asp-for="FlaggedStatus" type="checkbox"> Flag Address
 </label>
</div>

Which looks like this on the form unchecked:

enter image description here

and then like this when selected:

enter image description here

The binding works great for saving data. But when I load the form with data already entered, for edit mode, the checkbox is selected in the background, but the button does not show as filled in. So how do I bind it so the button will show as toggled on when the checkbox data is true?


Solution

  • The toggle uses the active css class on the parent label. Your going to have to use some inline logic:

    <label asp-for="FlaggedStatus" class="btn btn-outline-danger @(Model.FlaggedStatus ? "active")">