I get an error of "Cannot convert object of type System.String' to type 'System.Collections.Generic.List'1[...+ContactHolder]'"
This is my C# code:
public class ContactHolder{
public String Name { get; set; }
public String Address { get; set; }
}
[WebMethod]
public static string AddContact(Object items){
List<ContactHolder> contacts = new JavaScriptSerializer().ConvertToType<List<ContactHolder>>(items);
return String.Format("You added {0} contacts!", contacts.ToString());
}
This is my Javascript code (note I have included jquery-1.4.1.js and json2.js in my project)
function Test() {
var arr = new Array();
var contact = new Object();
contact.Name = "Ben";
contact.Address = "Ohio";
var contact2 = new Object();
contact.Name = "Jon";
contact.Address = "Illinois";
arr[1] = contact;
arr[2] = contact2;
var DTO = JSON.stringify(arr);
PageMethods.AddContact(DTO, OnMyMethodComplete);}
function OnMyMethodComplete(result, userContext, methodName) {alert(result);}
When I pass DTO into myPageMethod it looks like this: "[{"Name":"Ben","Address":"Ohio"},{"Name":"Jon","Address":"Illinois"}]"
When it appears in my WebMethod as items it looks like this: "[{\"Name\":\"Ben\",\"Address\":\"Ohio\"},{\"Name\":\"Jon\",\"Address\":\"Illinois\"}]"
The code errors on the call to JavaScriptSerializer().ConvertToType, the message is {"Cannot convert object of type System开发者_JAVA技巧.String' to type 'System.Collections.Generic.List'1[...+ContactHolder]'"}
What do I need to do to make this work?
Passing parameter to WebMethod with jQuery Ajax
Remove JSON.stringify
or do like this:
sending JSON object successfully to asp.net WebMethod, using jQuery
精彩评论