I'm having a class like the following:
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
[DataContract()]
public class TestCol : List<Test> { }
[DataContract()]
public class MainTest
{
public TestCol Components { get; set; }
}
[DataContract()]
public class Test
{
public Test() { }
public String Name { get; set; }
}
And a webservice with the following webmethod like this:
[WebMethod]
public String Test(MainTest input)
{
String rtrn = String.Empty;
foreach (Test test in input.Components)
rtrn += test.Name;
return rtrn;
}
Which is called by AJAX with the following method:
var Test = {};
Test.Name = "Test";
var MainTest = {};
MainTest.Components = [];
MainTest.Components.push(Test);
$.ajax({
type: "POST",
url: "WebService/WSTest.asmx/Test",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({
"input": MainTest
}),
success: function(data, textStatus) {
console.log("success");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
window.console && console.log && console.log(XMLHttpRequest.responseText + " || " + textStatus + " || " + errorThrown);
}
});
When executing the AJAX call, it will return errors. I found out that the error is with the typed class TestCol
, which has no properties.
Now do I have found 2 solutions that require changes in the C# classes:
Remove the
TestCol
class and change theComponents
property toList<Test>
datatype:[DataContract()] public class MainTest { public List<Test> Components { get; set; } } [DataContract()] public class Test { public Test() { } public String Name { get; set; } }
Or add an extra property to the
TestCol
class and change the webmethod:[DataContract()] public class TestCol : List<Test> { public List<Test> Components { get; set; } } [DataContract()] public class MainTest { public TestCol Components { get; set; } } [DataContract()] public class Test { public Test() { } public String Name { get; set; } }
&
[WebMethod] public String Test(MainTest input) { String rtrn = String.Empty; foreach (Test test in input.Components.Components) rtrn += test.Name; return rtrn; }
Both solutions require changes in the C# classes, which I prefer not to, as other code is depended on it. Does anyone know a solution for this problem?
Edit: I've uploaded a test solution, containing above code: http://jeroenvanwarmerdam.nl/content/temp/JSONtoClassWebservice.zip