Submit array param with jQuery ajax/load

…衆ロ難τιáo~ 提交于 2020-01-01 04:25:08

问题


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

trying to call the above method from jQuery:

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

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

the array paramater is null, other params are fine. What am I doing wrong?

Chrome developer tools shows form data being submitted as

arr%5B%5D%5B%5D:dog
arr%5B%5D%5B%5D:cat
someBool:true
someInt:1

not sure whats going on there but doesn't look right to me


回答1:


If you are using jquery 1.4 you might need to set the traditional parameter to true in order to be compatible with the default model binder format in 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);
    }
});

or if you prefer the .load() method:

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



回答2:


Just remove []

{ 'arr': test, 'someBool': true, 'someInt': 1 },

Posted values (checking with Firebug).

arr[]       dog
arr[]       cat
someBool    true
someInt     1
  • Example on jsFiddle



回答3:


can you see if this problem is similar to yours:

Passing an nested arrays to asp.net mvc using jQuery's $.ajax




回答4:


Even i was facing error, in passing array from HTML page to aspx page.

my requirement was to load the aspx page in a DIV tag of the html page. on the page load i need to pass these JS array values to aspx page load.

i used below method.

$('#<divTagID>').load("Targetpage.aspx",{"Arr":JSArrValues});

In aspx page load event i can access this values as:

string results = Response["Arr[]"];

Thanks to JQuery API documentation enter link description here and stackoverflow



来源:https://stackoverflow.com/questions/3942408/submit-array-param-with-jquery-ajax-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!