使用jQuery ajax/load提交数组参数

fea*_*net 14 asp.net-mvc jquery load paramarray

public ActionResult DoSomething(string[] arr, bool someBool, int someInt) { }

试图从jQuery调用上面的方法:

var test = [];
test.push('dog');
test.push('cat');

$container.load('MyController/DoSomething',
                { 'arr[]': test, 'someBool': true, 'someInt': 1 },
                function(response, status, xhr) {
                    // ...
                });
Run Code Online (Sandbox Code Playgroud)

数组参数为空,其他参数都很好.我究竟做错了什么?

Chrome开发人员工具会将提交的表单数据显示为

arr%5B%5D%5B%5D:dog
arr%5B%5D%5B%5D:cat
someBool:true
someInt:1
Run Code Online (Sandbox Code Playgroud)

不知道那里发生了什么,但看起来不对我

Dar*_*rov 28

如果您使用的是jquery 1.4,则可能需要将traditional参数设置为true以便与ASP.NET MVC中的默认模型绑定器格式兼容:

var test = [];
test.push('dog');
test.push('cat');

$.ajax({
    url: 'MyController/DoSomething',
    type: 'GET',
    traditional: true,
    data: { arr: test, someBool: true, someInt: 1 },
    success: function(result) {
        $container.html(result);
    }
});
Run Code Online (Sandbox Code Playgroud)

或者如果您更喜欢这种.load()方法:

var data = { arr: test, someBool: true, someInt: 1 };
$container.load('MyController/DoSomething', $.param(data, true), 
    function(response, status, xhr) {
    // ...
});
Run Code Online (Sandbox Code Playgroud)