简体   繁体   中英

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:

{"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:

{"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. I thought MVC handles this correctly by binding the true value and not the value from the hidden input for checkbox.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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