Search code examples
javascriptrazorasp.net-mvc-5jquery-ajaxqcheckboxfor

Issue with @Html.CheckBoxFor always posting false via $.Ajax Post Method in ASP.NET-MVC5 App


I trying to post data via jQuery Ajax function in JSON format which is working fine, howerver I have bool value and using html.checkBoxFor which is always posting false even I check it. I have update code in javaScript and force change the hidden input value accordingly if its check or not and I can see in debuging that is posting true when clicked but still receiving false on controller side. In attached screen shots you can see the post correct value but not in-correct value on controller

enter image description here

enter image description here

Model Class Attribute

  [Display(Name = "Secure Entire Property")]
  [Required(ErrorMessage = "Require Information on If You Want to Secure Entire Property")]
  public bool SecureEntireProperty { get; set; }

Razor code

<div class="form-group">
   @Html.LabelFor(model => model._RentingApplicationModel.SecureEntireProperty, htmlAttributes: new { @class = "control-label col-md-2" })
 <div class="col-md-10">
    <div class="checkbox">
     @*@Html.EditorFor(model => model._RentingApplicationModel.SecureEntireProperty)*@
     @Html.CheckBoxFor(model => model._RentingApplicationModel.SecureEntireProperty, new { @id = "SecureEntirePropertyCheck" })
     @Html.ValidationMessageFor(model => model._RentingApplicationModel.SecureEntireProperty, "", new { @class = "text-danger" })
       </div>
    </div>
  </div>

JavaScript

 $("#SecureEntirePropertyCheck").click(function () {

    if ($(this).is(':checked'))
    {
        $('[name="_RentingApplicationModel.SecureEntireProperty"]:hidden').val(true);
    }
    else
    {
        $('[name="_RentingApplicationModel.SecureEntireProperty"]:hidden').val(false);
    }
});

Jquery Ajax Method Where I am Posting

 $.ajax({
        url: formURL,
        type: "POST",
        dataType: "application/json",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ TenentJSONList: AdditionalTenentList, ApplicationModelData: $("#CreateStudentRentingApplicationForm").serializeObject() }),
    }).done(function (data, textStatus, jqXHR) {
        //....my rest of code 

AdditionalTenentList

<script type="text/javascript">

 var AdditionalTenentList = new Array();

 $(".additionalTententUWLID").on("change", function () {

 var StudentUWLID = $(this).val();

 $(this).attr('id', StudentUWLID);

 $.ajax({
        url: '@Url.Action("GetStudentRecordByID", "StudentProfile")',
            type: "POST",
            dataType: "JSON",
            data: { _GivenStudentUWLID: StudentUWLID },
            cache: false
        }).done(function (data, textStatus, jqXHR) {

            if (data.RecordStatus == "NotAvailable")
            {
                alert("error");
            }
            else if(data.RecordStatus=="recordFound")
            {
               // alert(data.Response);

                var paraedData = JSON.parse(data.Response);

                AdditionalTenentList.push(StudentUWLID);
           ....my rest of code
</script>

Solution

  • Your problem is that your posting an array of values for the SecureEntireProperty property and a boolean property cannot be bound to an array.

    What you should be seeing in the 'Post' tab if the checkbox is checked is

    ....
    _RentingApplicationModel.SecureEntireProperty: true
    _RentingApplicationModel.SecureEntireProperty: false
    ....
    

    and just the second one if its unchecked. The DefaultModelBinder reads the value of the first one (true) and sets the property. It ignores any subsequent values that match the same property.

    I assume this is because of your use of .serializeObject(). That is not a native jQuery method so either your using a plugin or have written your own function (perhaps something like this one?). In any case it is not generating the correct post values. Instead use the jQuery .serialize() function to serialize the form values. Because you also posting an additional array of value, you will need to modify your code to

    var data = $('#CreateStudentRentingApplicationForm').serialize() + '&' + $.param({ 'TenentJSONList': AdditionalTenentList }, true);
    
    $.ajax({
        url: formURL,
        type: "POST",
        dataType: "application/json",
        data: data,
    }).done(function (data, textStatus, jqXHR) {