2

I have tried many stackoverflow posts, but I have always the same result. The passed int array always null.

Pass array to mvc Action via AJAX

Here the asp.net mvc action which accept the int array of ids.

[HttpPost]
public ActionResult Downloads(int[] ids){
    return RedirectToAction("Exports", ids);
}

This is the ajax call, which is send the values.

var url = '@Url.Action("Downloads")';
var values = [1,2,3];
$.ajax({
    url: url,
    type: 'POST',
    dataType: "json",
    contentType: 'application/json; charset=utf-8',
    traditional: true,
    data: JSON.stringify({ids: values })
});

I have no idea what I make wrong. I have passed the ajax's date like a simple array: data: values or without stringify, but the asp.net mvc never accept the int array. It seems the traditional parameter of ajax object does not do anything.

Dabagab
  • 2,497
  • 4
  • 26
  • 31

2 Answers2

2

If you want to send values using traditional encoding then you shouldn't JSON encode the data you're sending. As such, remove the JSON.stringify() call, as well as the contentType. Try this:

$.ajax({
  url: url,
  type: 'POST',
  dataType: "json",
  traditional: true,
  data: { ids: values }
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

Just remove JSON.stringify it will work.

[HttpPost]
public JsonResult Test(int[] ids)
{
   return Json("Integers. " + ids);
}

//In Jquery please put this.

var PostData = {};
PostData.ids = [1, 2, 3, 5];
var ajaxOptions = {
        type: "POST",
        url: '@Url.Action("Test", "Settings")',//Actionname, ControllerName
        data: PostData,
        dataType: "json",
        success: function (result) {
            console.log(result);
        },
        error: function (result) {

        }
};
$.ajax(ajaxOptions);
Negi Rox
  • 3,828
  • 1
  • 11
  • 18