1

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>
K.Z
  • 5,201
  • 25
  • 104
  • 240
  • Why are you updating the hidden input (don't do it - its supposed to post back `false`!). And the `[Required]` attribute is not really necessary - a `bool` only has 2 values and it will be either `true` or `false` and never `null`. –  Aug 04 '15 at 08:06
  • I haven't change the hidden input value in my initial attempt but I was always getting false, thought it can help me ... – K.Z Aug 04 '15 at 08:35
  • I am not sure what I am doing wrong here! – K.Z Aug 04 '15 at 08:35
  • I'll look at in detail at bit later, but can you try `serialize()` instead of `serializeObject()` –  Aug 04 '15 at 08:42
  • Ok, I try in a minute – K.Z Aug 04 '15 at 08:46

2 Answers2

2

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) {
Community
  • 1
  • 1
  • Many thanks first of all for helping me! I have change .serializeObject() to serialize() and I am getting null value for #CreateStudentRentingApplicationForm however I am getting value of TenentJSONList – K.Z Aug 04 '15 at 10:28
  • OK, I think I know what the other issue is. Can you try just `data: JSON.stringify($("#CreateStudentRentingApplicationForm").serialize()),` and see if that binds to your model. –  Aug 04 '15 at 10:30
  • Or alternatively `data: $("#CreateStudentRentingApplicationForm").serialize(),` and remove the `contentType: "application/json; charset=utf-8",`.One of those 2 options should bind your model. –  Aug 04 '15 at 10:36
  • Ok, I have tried following and managed to pass Model data with true value but NOW I am getting null value for AdditionalTenentList ............ data: JSON.stringify({ enentJSONList: AdditionalTenentList, ApplicationModelData: $("#CreateStudentRentingApplicationForm").serialize() }), – K.Z Aug 04 '15 at 10:45
  • Which one of the 2 options above did you try - or did both work (and I know `AdditionalTenentList` would be null - it was just for testing :) You also need show what `AdditionalTenentList` is (the jquery code for constructing it) –  Aug 04 '15 at 10:50
  • Still getting null value for TenentJSONList: [AdditionalTenentList] – K.Z Aug 04 '15 at 10:50
  • OK, but can you also show how you generate `AdditionalTenentList` (it affect ajax options such as `traditional: true` which may need to be set) –  Aug 04 '15 at 11:06
  • I have update my question above at bottom ... refer to AdditionalTenentList heading – K.Z Aug 04 '15 at 11:09
  • Need a break for a while - I'll update the answer in an hour or so –  Aug 04 '15 at 11:10
  • @toxic, Refer edited answer. Note there is a bit cleaner way than using `+ '&' + $.param(...)` but cant remember the exact syntax but I'll check at work tomorrow (I always tend to use `FormData` now when combining form values with other values as per [this answer](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc/29293681#29293681)) –  Aug 04 '15 at 11:59
  • Thanks for this great post. The `serializeObject()` function you linked was the exact one causing issues for me as well in preventing the `Html.CheckBoxFor()` from binding correctly. – C. Helling Jun 16 '17 at 14:43
0

I had also faced this problem, then I came across this answer

I had added @Name attribute as follows

@Html.CheckBoxFor(m => m.IsPresent, new { @Name = "customName"})

This statement overrides the name that gets generated using @Html.CheckBoxFor

If you see html code generated by @Html.CheckBoxFor, you'll see two input tags generated. so I just removed @Name attribute and I was able to submit the request using Ajax as follows:

if ($(this).valid()) {
   $.ajax({
     url: this.action,
     type: this.method,
     data: $(this).serialize(),
     traditional: true,
     success: function (data) {
          //.........
     }

Now i'm able to receive value submitted through checkbox.

Gambitier
  • 504
  • 6
  • 18