简体   繁体   English

Model属性总是从复选框中获取false值,即使它的检查也是如此。 数据是来自ajax调用的json

[英]Model property always get false value from a checkbox even if its check. data is json from ajax call

I have a form that when submitted will call the code below: 我有一个表单,提交时将调用以下代码:

$.ajax({
        url: '/Company/CheckError',
        type: 'POST',
        data: JSON.stringify($(this).serializeObject()),
        dataType: 'json',
        processData: false,
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
    }
});

if my IsActive checkbox is unchecked I found out that it returns the following json data: 如果未选中我的IsActive复选框,我发现它返回以下json数据:

{"Email":"test@test.com","Name":"test","Phone":"","IsActive":"false","submitType":"","Id":"59"}

which I found natural. 我觉得很自然。 But if checked the IsActive checkbox, it will return this json data: 但是如果选中了IsActive复选框,它将返回此json数据:

{"Email":"test@test.com","Name":"test","Phone":"","IsActive":["true","false"],"submitType":"","Id":"59"}

Now in my controller, 现在在我的控制器中,

public ActionResult Method(SomeModel model)
{

}

the other property binds just fine. 另一个属性绑定得很好。 But the model.IsActive is always false. 但是模型.IsActive总是假的。 I thought MVC handles this correctly by binding the true value and not the value from the hidden input for checkbox. 我认为MVC通过绑定真值而不是隐藏输入的值来正确处理这个问题。

Am I missing something? 我错过了什么吗? Advance thanks for your help =') 预谢谢你的帮助=')

Try like this: 试试这样:

Model: 模型:

public class SomeModel 
{
    public bool IsActive  { get; set; }
}

Controller: 控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new SomeModel();
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(SomeModel model)
    {
        return Json(new { success = model.IsActive });
    }
}

View: 视图:

@model SomeModel

@using (Html.BeginForm())
{
    <div>
       @Html.LabelFor(x => x.IsActive)
       @Html.CheckBoxFor(x => x.IsActive)
    </div>
    <p><input type="submit" value="OK"></p>
}

<script type="text/javascript">
    $('form').submit(function () {
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function (data) {
                alert(data.success);
            }
        });
        return false;
    });
</script>

将以下内容添加到控制器方法中:

model.IsActive = model.IsActive.Contains("true");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM