在Ajax中捕获复选框值

catching checkbox value in Ajax

本文关键字:复选框 Ajax      更新时间:2023-09-26

我在部分视图中有一个复选框

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

在同一个局部视图中,我有以下Ajax代码:

<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);
        }
    }
    );
}

但它每次都会传回一个False值。

我对@Html.EditorFor使用了同样的方法,没有遇到任何问题——有人能帮我指出哪里出了问题吗?

谢谢:)

编辑

认为问题出在新的html属性=new。。删除了(并更正了打字错误)

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

然后使用

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

并且no返回1或0。

我的猜测:

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

ID不匹配

这是我在构建的表单映射器中使用的:

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

因此,您可能需要将$("#txtIsFullTime").val()更改为$("#txtIsFullTime").get(0).checked$("#txtIsFullTime").is(':checked')

更新

我相信10的值是因为Html.CheckBoxFor()产生2个输入。一个用于值(0|1),一个用于状态(true|false)。这是MVC级别的要求。

更多信息