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>
Add the following into your controller method:
model.IsActive = model.IsActive.Contains("true");
精彩评论