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?

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

6 Comments

But in my case, even though the checkbox is checked I am getting false in controller??
Show you controller method and the relevant property in the model.
Looks OK (but why the [Bind(Include="....")]?). Do you have any javascript (perhaps disabling the checkbox which means it wont post back)?
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
I have found the solution. when I removed Bind[] . it started working correct. But still I don't know what went wrong :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.