Returning a Generic Collection from a Web Service
So far, you have seen how to perform data binding with a generic collection returned by the data access layer object. This section discusses how to return generic collections from a Web service, which has the advantage of letting client applications bind directly to the output returned by the Web service method.
The following code shows how to return a generic collection from a Web service. It leverages the CategoryDB class you've already seen to retrieve data from the AdventureWorks database.
<%@ WebService Language="C#"
public class CategoryService :
public List<Category> GetCategories()
CategoryDB category = new
|Figure 2. CategoryService Output: The figure shows the XML for the generic collection object returned by the CategoryService Web service. Note that the Web service returns the collection as an array of Category objects.|
In the preceding code, the GetCategories()
method simply invokes the GetCategories()
method of the CategoryDB class and returns the result to the Web service consumer.
Now, if you browse to the Web service using the browser and follow the on-screen directions to invoke the GetCategories()
method, you'll see the output shown in Figure 2
As you can see from the above figure, the .NET framework serializes the generic collection as an array of Category objects when invoked from the browser. You can then easily bind this array of Category objects to data bound controls in the client application.
Keep It Short
As you can see, the ability to leverage generics as the middle tier return type opens up a whole avenue of new and interesting opportunities to work with data in the user interface layer. Using the techniques shown here, you can now easily serialize, deserialize, and databind generic types and collections. In addition, you can also return generic types from your Web service that can then be seamlessly consumed by client applications.