john
john

Reputation: 4158

Trying to pass javascript array and int to codebehind

I am trying to pass a javascript array to a method in my code behind. The problem is, I need to pass an int to the method along with the array. When I do:

$.ajax({
                type: "POST",
                url: webMethod,
                data: JSON.stringify({ myArray : passedArray }),

it works. But now i can't seem to figure out how to pass the array to the code behind AND an int. I need to pass this with the array:

"{'selectID' : '" + $("#ScarTattoos option:selected").val()

since my method paramters are:

public markItem getMarkNoID(int selectID, string[] person)
{
}

Upvotes: 0

Views: 630

Answers (4)

beatgammit
beatgammit

Reputation: 20205

Try something like this:

var obj = {
    selectID: parseInt($("#ScarTattoos option:selected").val(), 10),
    myArray: passedArray
};

$("#ScarTattoos option:selected").val() will give you a string, so you need parseInt() to make it a number type.

Just JSON.stringify your obj and send it.

Upvotes: 1

Pow-Ian
Pow-Ian

Reputation: 3635

I would suggest adding the array and the int to an object and stringify-ing that object.

var theID = $("#ScarTattoos option:selected").val();
var array = passedarray;
var PassObj = { selectID: theID, person: array};

Upvotes: 1

Honza Brestan
Honza Brestan

Reputation: 10947

You can send a composite JSON object, like this:

{
    myArray: passedArray,
    selectID: $("#ScarTattoos option:selected").val()
}

Pass this to JSON.Stringify in your AJAX call and both desired objects will be sent to the server handler.

You'll have to deserialize it manually though, unless you're sending it to a web service, which usually does the deserialization itself based on parameter names (when in JSON mode).

Upvotes: 4

andleer
andleer

Reputation: 22568

Not sure you can simply POST from a jquery ajax method to your code behind. If you were developing with MVC, yes you can POST to a controller but you appear to be using web forms. You will likely have better luck saving your JSON data to a <asp:HiddenField /> and then posting back.

You can get the required Postback JavaScript code by invoking the Page.ClientScript.GetPostBackEventReference() method on the server and then passing the result to your client side JavaScript code for later invokation.

Upvotes: 1

Related Questions