Receive an array into the controller from javascript

Question:

I'm creating an array with a list of data in javascript:

var myArray = gvSortingListagemGARs.keys;

Where do I have the result:

[278, 279, 280, 281, 282]

Which are element id's of a Devexpress table. Now I'm trying to pass this array to my controller, it's just always getting null .

my js function

function downloadListaGARSTratadas() {
    var myArray = gvSortingListagemGARs.keys;
    alert(myArray);
    window.location.href = "/GAR/downloadListaGARsTratadas?GarsFiltro=" + myArray +"";
}

Role in controller

public ActionResult downloadListaGARsTratadas(int[] GarsFiltro)
{ ... }

If I do string instead of int[] I get 278, 279, 280, 281, 282 , that is, the variable. Can't get even with an integer array?

Answer:

You must specify that this is an array like this and pass each value as a parameter, but all with the same name, for example:

/?arr[]=foo+bar&arr[]=baz&arr[]=foo

Or even so for some cases (such as ASP MVC):

/?arr=foo+bar&arr=baz&arr=foo

As demonstrated in this and this SO-EN topic and this post

So in your case you should do something like:

window.location.href = "/GAR/downloadListaGARsTratadas?GarsFiltro=1&GarsFiltro=2&GarsFiltro=3"

To generate this parameter dynamically I created this method:

function formatQueryStringURLParamArray(key, array){
    var param = "";
    for(var item in array){
        if(param.length > 0)
            param += "&";
        param += key + "=" + item;
    }
    return param;
}

Which can be called this way, returning the formatted querystring:

var param = formatQueryStringURLParamArray("key", myArray);

Here's an example online .

Example with Web API

Try the following test (I use WebApi ASP MVC, but it's very similar to MVC):

I created the following ApiController:

public class Test2Controller : ApiController
{
    [HttpGet]
    public virtual int Get([FromUri]int[] i)
    {
        return i.Length;
    }
}

And I made the following request via url in my browser:

http://localhost:59402/api/test2/?i[]=1&i[]=2&i[]=3

And I correctly received the integer array.

I don't know if MVC uses this as I don't work with MVC just WebAPi, but try adding [FromUri] before your array parameter in Controller method.

Example with ASP MVC

I created this Controller:

public class Test3Controller : Controller
{
    [System.Web.Http.HttpGet]
    public ActionResult Index([FromUri]int[] i)
    {
        return Json(i, JsonRequestBehavior.AllowGet);
    }
}

And I made the following request via url in my browser:

http://localhost:59402/test3/?i=1&i=2&i=3

Note: I don't know why MVC didn't understand when I passed i[] , so if I just pass i={valor} , it does. The Web API worked in two ways: i={valor} and i[]={valor} .

Scroll to Top