I’m currently enabling JSON calls to my web services using the ScriptService attribute. The problem is that one of my classes references a second class and .Net is not picking up and writing out the JavaScript for the second class.
As a workaround I can write a dummy method that just returns the second class. Then .Net writes the JSON to allow it to be serialized. So in the following example:
[ScriptService] public class MyService : WebService { [WebMethod] public void SaveClass1(Class1 class1) { ... } } [Serializable] public class Class1 { public Class2 class2 { get; set; } } [Serializable] public class Class2 { }
MyService.asmx/js won’t write code to allow me to instantiate Class2 in order for me to populate Class1. But I can make it work if I add:
[WebMethod] public Class2 Dummy() { return new Class2(); }
to MyService. Any alternatives to my nasty workaround would be greatly appreciated.
You need to use System.Web.Script.Services.GenerateScriptTypeAttribute, which specifies that a server type should be included in the generated proxy code. You can apply this attribute to the web service itself or any method marked with WebMethodAttribute.
For example: