【问题标题】:How to post an array to mvc controller如何将数组发布到 mvc 控制器
【发布时间】:2019-06-26 12:16:25
【问题描述】:

我想将 java 脚本对象发布到 mvc 控制器

$(document).ready(function () {
        var table = $('#my_table_1').DataTable({
            "paging": true,
            "ordering": true,
            "info": true,
            "search": true,
            "pageLength": 100
});
var d = '';
var data3 = table.on('search.dt', function () {
    //number of filtered rows
    //  console.log(table.rows({ filter: 'applied' }).nodes().length);
    //filtered rows data as arrays
    d = table.rows({ filter: 'applied' }).data()
});
console.log(table.rows({ filter: 'applied' }).data());
$('#excel2').click(function (e) {
    //var data3 = table.on('search.dt', function () {         
    //    console.log(table.rows({ filter: 'applied' }).data());
    //    console.log(data3);
    //});
    console.log(d);
    $.ajax({
        url: '/Administrator/TestDownload',
        type: 'POST',
        data: {data:d},
        cache: false

    }).done(function (response) {
        alert(d);
       });
    });
});

//控制器代码:

public JsonResult TestDownload(String[] data)
    {
        return Json(data,JsonRequestBehavior.AllowGet);
    }

我在控制器中得到 null 作为数据参数

预期:想要从视图获取数据对象作为控制器中的参数。

实际:控制器中的数据参数为空

【问题讨论】:

  • 你能发布d变量的控制台日志吗

标签: arrays ajax asp.net-mvc


【解决方案1】:

您必须检查您的 d 变量是否正确的数组格式。

我用var d = ["test",2,3] 在我这边进行了测试,在控制器中它得到了正确的数据。

$('#excel2').click(function (e) {
    //var data3 = table.on('search.dt', function () {         
    //    console.log(table.rows({ filter: 'applied' }).data());
    //    console.log(data3);
    //});
    d = ["test",2,3]
    console.log(d);
    $.ajax({
        url: '/Administrator/TestDownload',
        type: 'POST',
        data: {data:d},
        cache: false

    }).done(function (response) {
        alert(d);
       });
    });
});

【讨论】:

    【解决方案2】:

    为什么不试试stringifying的数据和设置contentType

    $.ajax({
        url: '/Administrator/TestDownload',
        data: JSON.stringify({data:d}), // use JSON stringify
        type: 'POST',
        contentType: "application/json; charset=utf-8", //add this
        cache: false    
    }).done(function (response) {
        alert(d);
       });
    });
    

    【讨论】:

      【解决方案3】:

      一个有效的例子:

              var test = ["This", "is", "a", "test"];
              $.ajax({
                  type: "POST",
                  traditional: true,
                  url: "Administrator/TestDownload",
                  data: { array: test }
                  }
              });
      

      控制器(在 VB.net 中):

      Function TestDownload(array As String()) As ActionResult
      //do something
      End Function
      

      【讨论】:

        猜你喜欢
        • 2012-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-17
        • 2016-06-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多