Dabagab
Dabagab

Reputation: 2835

How pass int array from jquery ajax to asp.net mvc action

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.

Upvotes: 2

Views: 3973

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

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 }
});

Upvotes: 2

Negi Rox
Negi Rox

Reputation: 3922

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);

Upvotes: 0

Related Questions