在 Razor View 内部我有两个复选框属性。它们是相互排斥的。当其中一个被选中时,另一个则未被选中,反之亦然。
@Html.EditorFor(model => model.Before)
@Html.EditorFor(model => model.Start)
在 dom 就绪的同一 View 中,我管理复选框单击
$('#Before').change(function () {
if ($(this).is(":checked")) {
$('#Start').attr('checked', false);
return;
}
$('#Start').attr('checked', true);
});
$('#Start').change(function () {
if ($(this).is(":checked")) {
$('#Before').attr('checked', false);
return;
}
$('#Before').attr('checked', true);
});
此外,我正在创建 js 对象,该对象将被字符串化并发送到 mvc Controller
var myObj= {
Before: $("#Before").is(':checked'),
Start: $("#Start").is(':checked')
};
alert("Is before checked: "+$("#Before").is(':checked'));
alert("Is start checked: "+$("#Start").is(':checked'));
/* This returns always selected (correct) value */
$.ajax({
type: 'POST',
traditional: true,
contentType: 'application/json',
url: '/Home/Manage',
data: JSON.stringify({ model: myObj}),
success: function (data) { }
},error: function () {
alert('error');
}
});
我有代表这个 myObj 的 View 模型,它被发送到 Controller
public class MyViewModel
{
public bool Start { get; set; }
public bool Before{ get; set; }
}
[HttpPost]
public ActionResult Manage(MyViewModel model)
{
}
问题如下:
当选中“开始”时,我会得到“开始”为选中状态,而“之前”为未选中状态,这很好,但是当选中“之前”且“开始”未选中时,两者都会在模型中的 Controller 内部接收为 false。
最佳答案
尝试使用 .prop('checked', true);
而不是 .attr('checked', true);
关于javascript - 使用 jquery 管理复选框并将这些值发送到 Controller 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30343982/