Is there anyway to convert the @HTML.Checkboxfor into toggle html button? I have refer the toggle button style from https://www.w3schools.com/howto/howto_css_switch.asp
Currently its working by using :
@Html.CheckBoxFor(model => model.IsEnabled, new { @checked = "checked", @Name = "DelegateChkBox" })
Changed to:
<td class="slider-td">
<label class="switch">
<input name="DelegateChkBox" id="IsEnabled" type="checkbox" value="true" data-val-required="The IsEnabled field is required." data-val="true" data-bind="checked: IsEnabled">
<div class="slider round"></div>
</label>
</td>
The toggle button only works and postback to controller if it's CHECKED:
else it won't postback to controller by default UNCHECKED :
Any help will be appreciated! Thanks!
This is very simple, I have implemented in my project. You just need to keep the value of checkbox in a HiddenFor.
Then display your Toggle button in the page. For example,
So now when user check/uncheck the checkbox, call a jquery method and assign the value to @Html.HiddenFor(..). That's it.
Please check once this if ($("this").is(":checked")) instead if($(this).val()==true) and assign the value accordingly. Little busy, could not check my code :)
That's it. Now when you post back your page, you already set value to your IsEnabled field.
In Get method you have to do like the same. You just need to check the value of your HiddenFor() and take that value and assign to your HTML Toggle button in pageload event of js.
That's it. Please change the HTML accordingly.
Based from some experiments and findings, I found that you need to include hidden field generated by the helper (
Html.CheckBoxFor
) as shown by styling below:View usage example (just change
<input type="checkbox" />
to@Html.CheckBoxFor
):To ensure the checkbox is being checked in client-side before doing postback, you can use jQuery code below:
Demo example: .NET Fiddle
References:
Styling checkboxes in MVC 4
How can I apply a CSS style to Html.CheckBoxFor in MVC 5
@Html.checkboxfor - Get checkbox value using id