Receive an array in the controller from javascript

3

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

var myArray = gvSortingListagemGARs.keys;

Where I have the result:

[278, 279, 280, 281, 282]

That are id's of elements of a Devexpress table. Now I'm trying to pass this array to my controller, it's always always receiving null .

My js function

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

Function in controller

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

If I make string instead of int[] I get 278, 279, 280, 281, 282 , ie the variable. Can not receive even with an array of integers?

    
asked by anonymous 31.07.2014 / 13:09

4 answers

2

You should 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 for some cases (like ASP MVC):

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

As proven and on that SO-EN topic and in this post

Then in your case you should do something like this:

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

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

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

Here's a online example .

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 array of integers.

  

I do not know if MVC uses this, as it does not work with MVC WebAPi only, but try to add [FromUri] before its array parameter in the 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 do not know why MVC did not understand when I passed i[] , so if I only pass i={valor} , it understands. The Web API already worked in both ways: i={valor} and i[]={valor} .

    
31.07.2014 / 13:48
0

@CesarMiguel, the error you are having has nothing to do, but there is a second option to perform this process via ajax and using Json.

var myArray = gvSortingListagemGARs.keys;
var jsonString = JSON.stringify(myArray);
   $.ajax({
        type: "POST",
        url: "/GAR/downloadListaGARsTratadas",
        data: {data : jsonString}, 
        cache: false,

        success: function(){
            alert("OK");
        }
});
    
31.07.2014 / 14:10
0

I had a similar problem and found the following link:

p>

See if this helps you:

There is a parameter, called traditional , that you set in Ajax as true which sends the right javascript array to your controller. traditional : true,

I have an array, called shift, in my javascript that I will pass to my Controller via Ajax.

Shift is an array with the days of the week ... shift = ["Sunday", "Monday", "Tuesday", 4 more ...]

In javascript I have the call via Ajax ...

$.ajax({
        url: getBaseUrl() +  "GraphicsReport/FiltraDadosGrafico1",
        type: "POST",
        dataType: "json",
        traditional : true,
        data: {cDataInicial: dataInicial, cDataFinal: dataFinal, cLinha: linha, cTurno: turno, cModelo: modelo},
        cache: false,
        success: function (data) {
            //Faz alguma coisa...
        },
        error: function (data) {
           //Faz alguma coisa...
        }
    });

In my controller I get ...

public JsonResult FiltraDadosGrafico1(string cDataInicial, string cDataFinal, string cLinha, Array cTurno, string cModelo)
{
  string retCode = "Success";

  //Faz alguma coisa e retorna um Json

  return Json(new { retorno = retCode } );
}

See if this can help you. For me, it solved ...

    
29.09.2014 / 13:52
-1

As I could not solve this problem by returning a list of integers for the controller, I will leave here an answer with my solution (although that was not how I liked to solve it):

In the javascript function return the array to the controller as it had already done:

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

In the controller instead of receiving an array of integers, I had a string returned, returning the values as 201,202,203,204 :

public FileResult downloadListaGARsTratadas(string GarsFiltro)
{
   var arr = GarsFiltro.Split(',');
}

I made a split for the variable arr and it creates the array

    
31.07.2014 / 16:16