Click here to Skip to main content
15,885,141 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I am trying to pass an array from client to codebehind function.
The string that I am trying to pass looks like this:

[{"id":"1","name":"test","quantity":1}]

I get an ajax error: undefined. How do I pass this array?

Thanks,
Robert

The script:
JavaScript
function TestJSON() {
		var ItemRow = [];
		var Item = new Object();
		Item["id"] = "1";
		Item["name"] = "test"
		ItemRow.push(Item);

		var s = JSON.stringify(ItemRow);

		$.ajax({
			type: "POST",
			url: "Default.aspx/ReturnJSON",
			data: { "ItemRows": s },
			contentType: "application/json",
			dataType: "json",
			success: function (msg) {
				alert(msg.d);
			}
		});
	}


The HTML:
HTML
<input type="button" value="Test"  önclick="TestJSON()" /></form>


The codebehind:

C#
[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string [] ReturnJSON(string [] ItemRows)
{
   return ItemRows;
}
Posted
Comments
Kornfeld Eliyahu Peter 6-Feb-14 15:54pm    
Why string[]? IMHO it should be string only, as it's ain't a C# array!
Member 3493606 6-Feb-14 16:23pm    
I tried that already, I still get the error.
Any other suggestions?
Kornfeld Eliyahu Peter 6-Feb-14 16:34pm    
Add this to $.ajax, to see some error...
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}

To pass a string of parameters in Ajax call you have to first stringify the string as below. Let suppose you want to send two values as parameters than you have to do like this.

var params = JSON.stringify({ val1: "Value1", val2: 'Value2' });



and in
JavaScript
$.ajax{
......
........
........
data: params
}


Secondly to get these parameters in the Web Method you should define the web method definition with the same parameter names as defined in the string created above.

like to get the above passing parameters you have to create a web method like.

C#
[WebMethod]
   public static string GetData(string val1, string val2)
   {
//////////////Your code goes here....
   }


HOpe it will help you.. :)
 
Share this answer
 
Comments
norbitrial 7-Feb-14 2:23am    
That's even better! Nice one!
VICK 7-Feb-14 3:29am    
Thanks norbitrial.
Don't you think nicer deserves to be Upvoted? :D
norbitrial 7-Feb-14 3:47am    
That's true! :D
VICK 7-Feb-14 7:18am    
Thanks Buddy. :)
I finally figured it out: I am contstructing an array and sending it to my C# webmethod that accepts an array as parameter. The secret lies in the way you contruct the array object on the client, the format has to follow the format { var myObject = myarray : [] }}
Default.aspx:
JavaScript


JavaScript
function TestJSON() {
                // this is the array, notice the curly brackets around the array{}
		var JSONObject = { users: [] }; 
		var user;
		for (var s =0;s<3;s++)
		{
			user = { id: s, username: 'test' + s };
			JSONObject.users.push(user);
		}
      
		$.ajax({
			url: "Default.aspx/ReturnJSON",
			type: "POST",
			contentType: "application/json; charset=utf-8",
			data: JSON.stringify(JSONObject),
			async:false,
			cache: false,
			success: function (msg) {
				alert(msg.d);
			}
		});
	}
>


Default.aspx.cs
C#
[System.Web.Services.WebMethod]
public static string ReturnJSON(Users[] users)
{}


Thanks for all your help.
Robert
 
Share this answer
 
Why don't you just use Regex.Split method on server side to make array from string?

You can send your string with ajax to server side as the follows:
JavaScript
function TestJSON() {
   var stringForSend = 'first-second-third';

   $.ajax({
       type: "POST",
       url: "Default.aspx/ReturnJSON",
       data: '{ inputValuesForArray: "' + stringForSend + '" }',     
       contentType: "application/json",
       dataType: "json",
       success: function (msg) {
           alert(msg.d);
       }
   });
}


And you can catch and split the string with your choosen pattern:
C#
[System.Web.Services.WebMethod]
public static string ReturnJSON(string inputValuesForArray)
{
   string pattern = "-";

   string[] yourArray = Regex.Split(inputValuesForArray, pattern);

   return "I have found " + yourArray.Length.ToString() + " elements in the array!";
}


I hope this helps!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900