2

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.String' to type 'System.Collections.Generic.List'1[...+ContactHolder]'"}

What do I need to do to make this work?

Ben Hoffman
  • 8,149
  • 8
  • 44
  • 71
  • Can you post the implementation of `PageMethods.AddContact`? I think it would be more easier to help you if we know exactly what is going on behind the scenes. – Herberth Amaral Feb 15 '11 at 19:58
  • Why do you not declare the WebMethod parameter as ContactHolder[] ? Seems as if ASP.Net sees a scalar parameter (Object), and converts the JSON string into a .Net string. – devio Feb 15 '11 at 19:58
  • @Herberth - I do include the code for AddContact. It is in the C# code section. – Ben Hoffman Feb 15 '11 at 20:08
  • @Devio - I tried that, I get the same error. It just changes to can't convert into List. – Ben Hoffman Feb 15 '11 at 20:09

1 Answers1

4

Passing parameter to WebMethod with jQuery Ajax

Remove JSON.stringify or do like this:

sending JSON object successfully to asp.net WebMethod, using jQuery

Community
  • 1
  • 1
Artem Koshelev
  • 10,548
  • 4
  • 36
  • 68
  • 2
    This is correct. When using the ASP.NET AJAX service proxy helper methods, the parameters are automatically JSON serialized before sending. You *do* need the JSON.stringify() call if you're calling the service directly, without the service proxy. For example, if you're using jQuery's $.ajax(). – Dave Ward Feb 15 '11 at 20:35
  • Thanks Dave, I just found your answer in similar topic and linked it. – Artem Koshelev Feb 15 '11 at 20:36