简体   繁体   中英

How to handle arrays sent from jquery ajax with traditional : false

I'm having a bit of fun passing arrays from jquery ajax to a MVC.Net controller.

I have a couple parameters that I need to provide - here is the signature of the controller method:

public PartialViewResult GetMyPartial(Dictionary<int, string> param1, IEnumerable<int> param2) 

For some reason I can't get param2 to be passed to the server. On the client in JS I'm building the collections in the following manner:

var param1 = {};
$.each(someIntArray, function (index, value) {
    param1[value] = 'test' + index;
});

var param2 = [];
$('.someCheckbox[aria-expanded|=true]').each(function () {
    param2.push(parseInt($(this).val()));
});

I'm sending them in the following manner:

$.ajax({
...
    //traditional: true,
    data: {
        param1: param1,
        param2: param2
    },
...
});

This successfully passes param1, but not param2. If I uncomment the traditional: true then param2 is passed successfully, but not param1.

Is there a way to use the traditional mode on a single parameter? Or some way to get the controller to be happy with ?param2[]=1&param2[]=2 . At the moment it only seems to like ?param2=1&param2=2 .

I suspect that it may be down to how I'm building the collections which is why I've included that code.

Any help would be great - thank in advance.

If you're happy to send JSON, you could do

    data: JSON.stringify({
        param1: param1,
        param2: param2
    }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM