Reputation: 2433
What should the WebMethod's parameter be called below to get the json array sent from client? I used name
, but it didn't work.
var employees = {
"accounting": [ // accounting is an array in employees.
{
"firstName": "", // First element
"lastName": "Doe",
"age": 23
},
{
"firstName": "Mary", // Second Element
"lastName": "Smith",
"age": 32
}
], // End "accounting" array.
"sales": [ // Sales is another array in employees.
{
"firstName": "Sally", // First Element
"lastName": "Green",
"age": 27
},
{
"firstName": "Jim", // Second Element
"lastName": "Galley",
"age": 41
}
] // End "sales" Array.
} // End Employees
var toServer = JSON.stringify(employees);
This is the jquery ajax to send it to Web Method.
$("#sendtoServer").click(function () {
$.ajax({
type : "POST",
url : "Default.aspx/GetDetails",
data : '{name: "' + toServer + '" }',
contentType : "application/json; charset=utf-8",
dataType : "json",
success : OnSuccess,
failure : function (response) {
alert("Wrong");
}
});
function OnSuccess(response) {
alert("Sent");
}
});
And this is the Web Method
[System.Web.Services.WebMethod]
public static string GetDetails(string name)
{
var x=name;
return "";
}
Upvotes: 1
Views: 5660
Reputation: 8168
You have to rewrite your data initialization:
var employees = {
accounting: [ // accounting is an array in employees.
{
firstName: "", // First element
lastName: "Doe",
age: 23
},
{
firstName: "Mary", // Second Element
lastName: "Smith",
age: 32
}
], // End "accounting" array.
sales: [ // Sales is another array in employees.
{
firstName: "Sally", // First Element
lastName: "Green",
age: 27
},
{
firstName: "Jim", // Second Element
lastName: "Galley",
age: 41
}
] // End "sales" Array.
} // End Employees
$.ajax({
type: "POST",
url: "Default.aspx/GetDetails",
data: JSON.stringify({ name: employees }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert("Wrong");
}
});
function OnSuccess(response) {
alert("Sent");
}
use object parameter type on server side:
[System.Web.Services.WebMethod]
public static string GetDetails(object name)
{
var x=name;
return "";
}
Edit: The quotes removal is not needed as @Felix Kling pointed out.
Upvotes: 3
Reputation: 3412
You have to simply change your web method to:
[System.Web.Services.WebMethod]
public static string GetDetails(object name)
{
var x=name;
return "";
}
Upvotes: 2