Binding ObjectDataSource Control to a Web Service in ASP.NET

 

In this article we discuss about how to bind Wb Service to a ObjectDataSource Control and then how to bind ObjectDataSource control to Gridview. Here we bind the XML datasource to the Gridview control by using the ObjectDataSource control through DataClassContext object. 

Add EmployeeServices.asmx and add below code to codebehind file EmployeeServices.cs as shown below.

 

///<summary> 

/// Summary description for EmployeeServices 

///</summary>

 

[WebService(Namespace = http://tempuri.org/)] 

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 

 

// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.  

// [System.Web.Script.Services.ScriptService] 

public class EmployeeServices : System.Web.Services.WebService {

 

    public EmployeeServices () { 

 

 

        //Uncomment the following line if using designed components

         //InitializeComponent();

     }

 

    [WebMethod]

     public DataSet GetEmployees() { 

        DataSet dsEmployees = new DataSet();

         dsEmployees.ReadXml(Server.MapPath("Employees.xml"));

 

        return dsEmployees; 

    }

 

}

 

As show above, we are getting Employees details by using EmployeeServices.asmx web service. EmployeeServices.asmx has GetEmployees() method which returns all Employee details from XML file Employees.xml.

 

Now we have to bind this Employees detailsto the ObjectDataSource control. ObjectDataSource control expects TypeName and SelectMethod. Generally TypeName is the name of the class or web service name and SelectMethod is the name of the method in the class as shown below.

 

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml">

 

<head runat="server">

 

    <title>Binding Object DataSource with Web services</title>

 

</head>

 

<body>

 

    <form id="form1" runat="server">

 

    <div>

 

        <asp:ObjectDataSource ID="ObjSrc1" runat="server"   TypeName="EmployeeServices"   SelectMethod="GetEmployees" >       

        </asp:ObjectDataSource>

 

        <asp:GridView ID="gv1" runat="server" DataSourceID="ObjSrc1"></asp:GridView>

 

    </div>

 

    </form>

 

 </body>

 

</html>

 

In the above code, we provided the EmployeeServices as the TypeName and GetEmployees() as method name for ObjectDataSource control. Then provide this ObjectDataSource control id to the Gridview Databound control to display the data.

                                                                                                               ObjectDataSourceWebService.zip (4.31 kb)