6

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?

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Scratch that. You can actually send in the javascript array object if you turn on the traditional option.
@DoctorOreo Yup, that is what kept getting me. I had to pull out Fiddler to figure that one out :) Glad it was helpful to somebody else
3

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

1 Comment

traditional: true, /* I M P O R T A N T */ does the job. thanks!

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.