Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a List<int> from javascript to controller

Tags:

javascript

c#

I'm trying to pass a List<int> from my View to my Controller. I've tried multiple ways, with different parameters. No luck.

I'm currently trying to pass {[4,5,13]} to a method with the parameter List<int> ids.

What's the correct format to send a list or array of numbers?

like image 698
Cody Avatar asked Apr 18 '12 22:04

Cody


2 Answers

I believe that you have to pass in something like this:

{"ids":[4,5,13]}

If you are using AJAX, then I remember that I had to set traditional to true (See the jquery ajax documentation) This was so that the parameters were able to be parsed properly.

like image 115
Justin Pihony Avatar answered Oct 21 '22 12:10

Justin Pihony


The AJAX way:

From the jquery documentation for AJAX:

data

Type: PlainObject or String
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).

traditional

Type: Boolean
Set this to true if you wish to use the traditional style of param serialization.

var roleList = new Array();
var usrId = "testuser";

/* one  way of adding items to array */
roleList.push(1);
roleList.push(5);
roleList.push(8);

$.ajax({
            type: "POST",
            traditional: true, /* I M P O R T A N T */
            url: /* url to controller goes here */,
            data: { userId: usrId, allowedRoles: roleList },
            success: function(returndata) {
                alert("Done");
            },
            error: function(returndata) {
                alert("Error:\n" + returndata.responseText);
            }
        });
like image 24
BiLaL Avatar answered Oct 21 '22 11:10

BiLaL