我的Razor视图中有2个数组。第一个已选中复选框,第二个未选中。我可以发送其中之一,但我不知道如何发送两者。这是我的jQuery代码:
$(document).ready(function() {
$("#checkAll").click(function() {
$(".checkBox").prop('checked', $(this).prop('checked'));
});
$("#confrim").click(function() {
var selectedIDs = new Array();
var unseletedeIDs = new Array();
$('input:checkbox.checkBox').each(function() {
if ($(this).prop('checked')) {
selectedIDs.push($(this).val());
} else {
unseletedeIDs.push($(this).val());
}
});
var options = {};
options.url = "/Parts/ConfrimAll";
options.type = "POST";
options.data = JSON.stringify(selectedIDs);
options.contentType = "application/json";
options.dataType = "json";
options.success = function(msg) {
alert(msg);
};
options.error = function() {
alert("Error!");
};
$.ajax(options);
});
});
这是动作:
public ActionResult ConfrimAll(int?[] selectedIDs, int?[] unSelectedIDs)
{
if (selectedIDs!=null)
{
foreach (int id in selectedIDs)
{
Part obj = db.Parts.Find(id);
obj.IsOk = true;
db.Entry(obj).State = EntityState.Modified;
}
}
if (unSelectedIDs!=null)
{
foreach (int id in unSelectedIDs)
{
Part objs = db.Parts.Find(id);
db.Parts.Remove(objs);
}
}
db.SaveChanges();
return Json("yes");
}
最佳答案
您可以将这两个数组作为对象的一部分提供给data
调用的$.ajax
参数。尝试这个:
$("#confrim").click(function() {
var data = {
SelectedIDs: [],
UnSelectedIDs: [],
}
$('input:checkbox.checkBox').each(function() {
data[this.checked ? 'SelectedIDs' : 'UnSelectedIDs'].push(this.value);
});
$.ajax({
url: '/Parts/ConfrimAll',
type: 'POST',
data: data,
success: function(msg) {
console.log(msg);
},
error: function(x, s, e) {
console.log('Error!');
console.log(x, s, e);
}
});
});
请注意,将对象提供给
data
参数是一种更好的做法,因为jQuery随后将为您将其编码为所需格式,并在转义时转义任何特殊字符。关于javascript - 如何在MVC.NET中使用jQuery发送多个数组?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38452821/