0

My code is like this

<div class="form-group" style="padding-top: 30px;">
    @Html.CheckBoxFor(model => model.IsVatPaidByInsurer)
</div>

Inside Model Class

   public bool IsVatPaidByInsurer { get; set; }

Inside Controller

  public ActionResult Create([Bind(Include = "PayerID,Name,CreatedDate,PayerTypeSelected,ReferingInstitute,ApplicationUserId" +
                                               "IsVatPaidByInsurer,PatientContribution")] Payer payer)

I expect this line of code to generate a checkbox on front end, But how it renders is like this (value not true, it's I just checked the checkbox)

<div class="form-group" style="padding-top: 30px;">
    <input data-val="true" data-val-required="The IsVatPaidByInsurer field is required." id="IsVatPaidByInsurer" name="IsVatPaidByInsurer" type="checkbox" value="true">
    <input name="IsVatPaidByInsurer" type="hidden" value="false">
</div>

As you can see there is two inputs with same name generated (IsVatPaidByInsurer). And second one's value always false. So when I make my form post I can't get the real value of checkbox.It will interpret always as false there. Can anyone Tel me what This is whole about? and a way to overcome this?

None
  • 5,582
  • 21
  • 85
  • 170
  • possible duplicate of [ASP.NET MVC:Why does the CheckBoxFor render an additional input tag and how can I get the value using the FormCollection](http://stackoverflow.com/questions/2860940/asp-net-mvcwhy-does-the-checkboxfor-render-an-additional-input-tag-and-how-can) – Bryan Feb 23 '15 at 05:32

1 Answers1

1

The 2 inputs are correct (and without the hidden input you could get incorrect values). If the checkbox is checked, true, false is posted back and the DefaultModelBinder sets the model value to true (the second value is ignored). If the checkbox is unchecked false is posted back (unchecked checkboxes do not post back) so the model property is set to false

  • But in my case, even though the checkbox is checked I am getting false in controller?? – None Feb 23 '15 at 05:37
  • Show you controller method and the relevant property in the model. –  Feb 23 '15 at 05:38
  • Looks OK (but why the `[Bind(Include="....")]`?). Do you have any javascript (perhaps disabling the checkbox which means it wont post back)? –  Feb 23 '15 at 05:45
  • I have made a check on Chrome network tab. Data post back is correct Frist true then false both are sent back to server. But when I take payer.IsVatPaidByInsurer inside controller it is always false – None Feb 23 '15 at 05:52
  • I have found the solution. when I removed Bind[] . it started working correct. But still I don't know what went wrong :) – None Feb 23 '15 at 05:55
  • Sure you didn't spell it wrong? In any case, any time you find yourself using `[Bind(Include..)]` or `[Bind(Exclude..)]` **stop** and use a view model instead. –  Feb 23 '15 at 05:59