ASMX Web Service - Return user defined class with properties

Mikey picture Mikey · Oct 1, 2010 · Viewed 10.7k times · Source

Hey, I am trying to return a user defined class from a web method. The class has properties and/or methods. Given the following web method:

[WebMethod]  
public List<MenuItem> GetMenu()  
{  
    List<MenuItem> menuItemList = new List<MenuItem>();  
    menuItemList.Add(new MenuItem());  
    menuItemList.Add(new MenuItem());  
    menuItemList.Add(new MenuItem());  
    return menuItemList;  
}

Now, suppose this web service is consumed by adding a web reference in a newly created console application. The following code is used to test it:

public void TestGetMenu()  
{  
    MenuService service = new MenuService.MenuService();  
    service.MenuItem[] menuItemList = service.GetMenu();  
    for (int i = 0; i < menuItemList.Length; i++)  
    {  
        Console.WriteLine(menuItemList[i].name);  
    }  
    Console.ReadKey();  
}  

First of all, this doesn't work if the MenuItem class contains properties... Also, if the MenuItem class contains a method the call to the web method doesn't fail, but the method is not in the generated proxy class.. for example: menuItemList[i].getName() does not exist. Why? What am i missing?

//This works  
public class MenuItem  
{  
    public string name;  
    public MenuItem()  
    {  
        name = "pizza";  
    }  
}



//This crashes / doesnt work  
public class MenuItem  
{  
    private string name;  
    public MenuItem()  
    {  
        name = "pizza";  
    }  
    public string Name  
    {  
        get { return name; }  
        set { name = value; }  
    }  
}



//This successfully calls web method, but the method does not exist during test  
public class MenuItem  
{  
    private string name;  
    public MenuItem()  
    {  
        name = "pizza";  
    }  
    public string getName()  
    {  
        return name;  
    }  
}

Answer

Lloyd picture Lloyd · Oct 1, 2010

It will only work if the class is serializable which usually means public fields and properties, this is why your MenuItem will fail because your client side has no idea how to construct the MenuItem class properly.

Try this:

[Serializable]
public class MenuItem
{
   private string name;

   public MenuItem()
   {
      name = "pizza";
   }

   public string Name
   {
      get {
         return name;
      }
      set {
         name = value;
      }
   }

}