4

Using @Html.CheckBoxFor generates a hidden field. Is there a way I can avoid generating that ?

Why I want to do that ? I was provided design, which has some script or library used in it for visual display. It works fine if Html is in below format (Checkbox with Label):

<div>
                    <input type="checkbox" value="resources" id="resources" class="cb">
                    <label for="resources">
                        I need an offset facility
                    </label>
                    <i class="tooltip-icon" data-icon="repayments"></i>
                </div>

But it do not work if there is a hidden field between Checkbox and Label:

 <div>
<input id="HomeLoanLead_Redraw_flexibility_Value" class="cb" type="checkbox" value="true" name="HomeLoanLead.Redraw_flexibility_Value" data-val-required="The Redraw_flexibility_Value field is required." data-val="true">
<input type="hidden" value="false" name="HomeLoanLead.Redraw_flexibility_Value">
<label for="HomeLoanLead_Redraw_flexibility_Value"> I want to make extra repayments </label>
<i class="tooltip-icon" data-icon="loan"></i>
</div>

If I try using <input type=checkbox> I m afraid I will not get out of box model binding in post action.

Please help.

user576510
  • 5,777
  • 20
  • 81
  • 144
  • 3
    No, the helper generates a hidden input for good reason (unchecked checkboxes do not post back and it ensures a value is posted back for binding). Either adjust the script or inspect the html that the helper generates and re-create it manually (the hidden input just needs to be after the checkbox) –  Nov 10 '14 at 05:28
  • @StephenMuecke "(the hidden input just needs to be after the checkbox)", are you saying if I add html input tag and add a hidden field some where on post back I will not able to get value in model binding ? – user576510 Nov 10 '14 at 05:34
  • @StephenMuecke is there a way I can get values automatically bind to model in post back action if I use Html input type = checkbox ? – user576510 Nov 10 '14 at 05:36
  • 2
    By after, I mean anywhere after - it could be the last element in the form. –  Nov 10 '14 at 05:36
  • @StephenMuecke The thing I don't understand is I always always check the form values when returned, I use `"" + Request.Form["...` for take care of missing (null) form value. I'll never ever need that hidden field. – djack109 Jul 07 '17 at 14:15
  • Lots more discussion on this at https://stackoverflow.com/questions/2697299/asp-net-mvc-why-is-html-checkbox-generating-an-additional-hidden-input – Ruskin Aug 21 '17 at 13:26

0 Answers0