asp.net-mvc - 使用 jquery ajax 传递多个复选框值

标签 asp.net-mvc jquery asp.net-mvc-4

我在 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/

相关文章:

c# - 单个解决方案中的多个 MVC 项目

c# - 如何将模型中的列表作为 ajax 调用的参数传递?

javascript - jquery当前父子选择器

javascript - 如何在javascript中删除对象的一部分

JQuery - 突出显示导航中的当前选项卡

c# - 部分 View 未到达正确的位置

jquery - 更新 MVC4 Mobile 项目上的所有 nuget 包后 CSS 不起作用

c# - 无法转换类型为 'System.Data.Entity.DynamicProxies.Assignment...' 的对象

Android特定谷歌授权

asp.net-mvc - ASP.NET Web API 中简单属性的自定义类型转换器