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.

2
  • @RoryMcCrossan in this case I get a 'Invalid JSON primitive ids' error message. OK, content-type had to be removed too. Commented Nov 15, 2018 at 13:42
  • Glad you got it working, I added it as an answer for you below Commented Nov 15, 2018 at 13:54

2 Answers 2

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 }
});
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.