Receive an array in the controller from javascript

Asked

Viewed 3,610 times

3

I am creating an array with a javascript data list:

var myArray = gvSortingListagemGARs.keys;

Where I have the result:

[278, 279, 280, 281, 282]

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

My function js

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

Function in the controller

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

If you do string instead of int[] receiving 278, 279, 280, 281, 282, or is the variable. Cannot receive even with an integer array?

  • You must specify that it is an array like this: window.location.href = "/GAR/downloadListaGARsTratadas?GarsFiltro[]=" + myArray +"", at a glance at that link of SO-EN and in that who deal with this subject.

  • Yeah, and it makes sense to use GarsFiltro[]=" + myArray +"", but I still get null in the same

  • OK. is that I forgot a detail I will post as reply if I do not resolve I remove.

  • Are you not using Jquery? You would have more ease and control by making an ajax call.

  • Yes @lionbtt, I’m using jquery. I ended up doing it with javascript, but I can also try it with ajax. Although I don’t think the problem is from there

4 answers

2


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

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

Or still for some cases (such as ASP MVC):

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

As demonstrated in that and in that topic of SO-EN and in that 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 by 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 is 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 got the integer array correctly.

I don’t know if MVC uses this because I don’t work with MVC just Webapi, but try adding [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 don’t know why MVC didn’t understand when I was passing by i[], so if I just pass i={valor}, he understands. Already Web API worked both ways: i={valor} and i[]={valor}.

  • What you’re saying is that for every element of the array I have to do one GarsFiltro[]= ?

  • @Cesarmiguel, yes, I did not find documentation that says this, but this is how you do to pass array by querystring. I just don’t know if Asp mvc works. Tried?

  • Yes I tried now, I still don’t get the [1,2,3] I should receive using your example

  • @Cesarmiguel, are you receiving null? Or something else?

  • I am receiving null

  • @Cesarmiguel, take a look at the example I did with Webapi, in the answer edition, and check your controller.

  • @Cesarmiguel, from a look at the edition added an example with ASP MVC.

  • I have already seen your solution and still could not... I will post here an answer with a "solution" of this problem

Show 3 more comments

0

@Cesarmiguel, the error you are having has nothing to do, but follows 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");
        }
});
  • By ajax continues to give the same error. I had to add jQuery.ajaxSettings.traditional = true; before making the request (it worked)

0

I was having a similar problem and found the following link:

https://stackoverflow.com/questions/21288462/c-sharp-mvc-4-passing-javascript-array-in-view-to-controller

See if that helps you:

There is a parameter, called traditional, that you configure in Ajax as true that 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 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...
        }
    });

On 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, solved...

-1

Since I couldn’t solve this problem by returning a list of integers to the controller, I’ll leave an answer here with my solution (although that’s not how I wanted 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 integer array, I sent a string, 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

  • Cesar, the name of this is "Gambiarra", hehe, this is not a good approach, I tested it here with Webapi and MVC on Asp.net (MVC 4) and it worked my solution perfectly, recommend redoing my simple example in your environment and check why it’s not working (I assure you it works). If you have any questions I can help you.

  • @Fernando, I’ve just been testing your example and it really works!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.