0

I have a checkbox in a partial view

<div>Full time:  @Html.CheckBoxFor(model => model.FullTime, new { htmlAttributes = new { id = "txtIsFullTime" } })</div>

in the same partial view I have this Ajax code:

<script>
var urlAction = "@Url.Content("~/Treeview/_NewEmpThird")"; 
function AjaxGoodRedirect(urlAction) {           
    console.log(urlAction);
    $.ajax({
        type: "POST",
        url: urlAction,
        data: JSON.stringify({ FullTime: $("#txtIsFullTime").val() }),  //data: JSON.stringify({ ID: 1, Forename: "FName", Surname: "SName" }),
        datatype: "JSON",
        contentType: "application/json; charset=utf-8",
        success: function (returndata) {
            if (returndata.ok)
                $("#detailView").load(returndata.newurl);
            else
                window.alert(returndata.message);
        }
    }

    );
}

But it is passing back a False value every time.

I used the same method for an @Html.EditorFor and had no problems - can anyone help point out where i have gone wrong?

thanks :)

edit

Think the issue was with the new html attributes = new.. removed that (and corrected the typo)

div>Full time: @Html.CheckBoxFor(model => model.FullTime, new { id = "txtFullTime" })

then used

data: JSON.stringify({ ID: $("#txtFullTime").is(':checked') ? 1 : 0 })

and no returns 1 or 0.

JQuery
  • 889
  • 3
  • 13
  • 35

2 Answers2

0

This is what I use in a form mapper that I've built:

switch (field.prop('type')) {
    case 'checkbox':
        newVal = this.checked;
        break;
    default:
        newVal = field.val();
        break;
}

So you probably have to change $("#txtIsFullTime").val() to $("#txtIsFullTime").get(0).checked or $("#txtIsFullTime").is(':checked')

UPDATE

I believe the value 1 or 0 is because an Html.CheckBoxFor() generates 2 inputs. One for the value (0|1), one for the state (true|false). This is a requirement on MVC level.

More info

Community
  • 1
  • 1
Tim Vermaelen
  • 6,869
  • 1
  • 25
  • 39
  • If the downvote is only based on the ID mismatch, correct the ID and then you still have an issue using `.val()` ... just saying ... – Tim Vermaelen Apr 08 '15 at 15:48
  • Hi, I didn't downgrade this. Yep you are right with the typo, i had previously corrected that and still didn't work. – JQuery Apr 09 '15 at 06:59
  • .checked kicks off a syntax error and the second one doesn't seem to capture it either as still returning false. same as .prop('checked') – JQuery Apr 09 '15 at 07:10
0

My guess:

id = "txtIsFullTime"
$("#textIsFullTime")

ID mismatch

Josh Hancock
  • 795
  • 10
  • 15