我在 ASP.NET MVC 4 View 上显示多条记录,其中每条记录都有一个复选框。我希望用户能够选择多个记录(通过选中复选框)并单击“删除”按钮以删除它们。到目前为止,我可以通过 jquery ajax 调用删除操作方法,但问题是我的操作方法似乎不接受传递的数组。 这是我的 jquery 代码:
$(function () {
$.ajaxSetup({ cache: false });
$("#btnDelete").click(function () {
$("#ServicesForm").submit();
});
$("#ServicesForm").submit(function () {
var servicesCheckboxes = new Array();
$("input:checked").each(function () {
//console.log($(this).val()); //works fine
servicesCheckboxes.push($(this).val());
});
$.ajax({
url: this.action,
type: this.method,
data: servicesCheckboxes,
success: function (result) {
if (result.success) {
}
else {
}
}
});
return false;
});
});
这是我的操作方法:
[HttpPost]
public ActionResult DeleteServices(int[] deleteservice)
{
if (deleteservice != null)
{
//no hit
}
}
我错过了什么?
编辑
我还在 $.ajax()
之前尝试过 console.log(servicesCheckboxes);
输出 ["3", "4"]
但当我传递下面的答案中指定的数据时仍然为 null data: { deleteservice: servicesCheckboxes }
。即使我尝试了 data: [1,2]
但操作方法仍然在操作方法中显示 deleteservice
为 null。
最佳答案
只需将数组传递给您的操作即可:
$.ajax({
url: this.action,
type: this.method,
dataType: "json"
data: { deleteservice: servicesCheckboxes }, // using the parameter name
success: function (result) {
if (result.success) {
}
else {
}
}
});
或者,只需使用 serialize()
jquery 方法序列化表单中的所有字段:
$.ajax({
url: this.action,
type: this.method,
dataType: "json"
data: $(this).serialize(),
success: function (result) {
if (result.success) {
}
else {
}
}
});
在你的 Controller 中:
[HttpPost]
public ActionResult DeleteServices(int[] deleteservice)
{
bool deleted = false;
if (deleteservice != null)
{
// process delete
deleted = true;
}
return Json(new { success = deleted });
}
关于asp.net-mvc - 使用 jquery ajax 传递多个复选框值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14570759/