Please make sure that you have read XML Web Services: Part 1: Overview and database interaction as this example builds on the previous example and code.
Now that you understand how XML Web Services and .NET fit together and have learned how to create a XML Web Service, this tutorial will show you how to consume the previous service in an ASP.NET page (which you can use as a model to consume other Web Services).
To access our service we will be using HTTP-GET and then binding the data to a DataGrid. Below is the code to consume our service.
<%@ Import Namespace="System.Xml" %>
<script language="C#" runat="server">
public void Page_Load(Object sender, EventArgs e){
if (!IsPostBack){
XmlDataDocument mydata = new XmlDataDocument();
mydata.DataSet.ReadXml("http://myserver.com/xmlwebservice_data.asmx/GetData?");
MyGrid.DataSource = mydata.DataSet;
MyGrid.DataBind();
}
}
</script>
<center>
<form runat="server">
<asp:DataGrid id="MyGrid" runat="server"
BorderColor="black"
Border="0"
BorderWidth="0"
CellPadding="3"
Width="500"
ShowHeader="true"
AutoGenerateColumns="true">
</asp:DataGrid>
</form>
</center>
|
How easy is that? If you've read our past articles on using XML with .NET, the code should look very familiar. After creating an instance of XmlDataDocument you need to set the DataSet property using the DataSet method ReadXml to access the Web Service and get the returned XML data.
Notice that when calling the Web Service we are calling the url, the name of our ".asmx" file and specifying the method to use in the service with /GetData? (if we needed to specify an input value we would do that with /GetData?parameter=value as in /GetData?Search=superdotnet).
Once the information is loaded, we just need to set the XmlDocument's DataSet as the DataGrid's DataSource and bind the control. After that, it works just like a normal DataGrid returning the columns and values.