Simplified and Extended Data Binding Syntax in ASP.NET 2.0 -- Cont'd

The New Data Binding Syntax for XML Data

Increasingly, the data you have to work with in your Web applications is presented as XML. It might be static XML documents, or (more likely) XML that has been dynamically generated by another application or a Web Service. ASP.NET 2.0 contains several new data source controls, and three of these are specifically designed to work with XML data:

  • The XmlDataSource control is designed to work with hierarchical data presented as XML, in other words data where there can be multiple and irregular nesting of elements.

  • The DataSetDataSource control is designed to work with XML that represents a flat table, rather than being hierarchical in nature. In other words, XML data that effectively represents a DataTable within a DataSet.

  • The SiteMapDataSource control is a logical extension of the XmlDataSource control and is specifically designed to expose an XML-formatted map of a Web site or application. It is generally used along with several other new controls in ASP.NET 2.0 that generate menus and other site navigation aids.
This article does not explore the new data source controls, but instead focuses on the way that data binding is used to access and present individual items of data that these controls expose.

The XPathBinder Object

The issue at hand is: how do you specify an element or a series of elements when creating output where the data is XML rather than the more usual "rows and columns" format? The existing Eval and Bind methods rely on the column names and are used when the source data is a rowset - such as that exposed by the SqlDataSource control.

The answer is that there is a new binding object in ASP.NET 2.0, called the XPathBinder. This works much like the DataBinder object that is now the default context when data binding to rowset data. The XPathBinder object exposes two methods that can be used to select items from an XML document, the Eval method and the Select method.

The Eval method, which has exactly the same syntax as the DataBinder.Eval method, returns the value of a single element or attribute from the current context. The current context is effectively the set of elements exposed by the parent of this element, rather like the set of columns in the current row of a relational data rowset. You can optionally format the returned value using the same approach as described for the DataBinder.Eval method:


<%# XPathBinder.Eval(Container.DataItem, "xpath"[, "format"]) %>

However, in line with the simplified syntax for rowset data binding, the equivalent has been provided for XML data sources as well. Rather than specifying the XPathBinder.Eval method, you simply use a method of the TemplateControl named XPath:

<%# XPath("xpath"[, "format"]) %>

The second method of the XPathBinder is the Select method. This method is designed to return a collection of node values, rather than a single value (like the Eval/XPath method does). For this reason, there is no format parameter for the Select method. The full syntax of this method is:

<%# XPathBinder.Select(Container.DataItem, "xpath") %>

Again, there is a simplified form:

<%# XPathSelect("xpath") %>

The xpath parameter to the XPath and XPathSelect methods is an XPath expression that identifies the nodes that you want to bind to the controls in your page. XPath expressions are extremely powerful, and can be used to return single nodes (elements or attributes) from anywhere in an XML document, or collections of nodes. For more details of XPath and the techniques for writing XPath expressions, start at the W3C site at http://www.w3.org/TR/xpath.

Using the XPath Method To demonstrate the XPath method, we need some XML to act as the source data. For simplicity, this example uses a disk file named employees.xml, which looks like this:


<?xml version="1.0" ?>
<employee-list>
  <employee id="2456">
    <name>Mike</name>
    <department>Sales</department>
    <phone>3867</phone>
  </employee>
  <employee id="1965">
    <name>Nikita</name>
    <department>Marketing</department>
    <phone>1442</phone>
  </employee>
  ... more employees here ...
</employee-list>

To expose this for data binding, we use an XmlDataSource control, specifying the disk file as the XML source data:

<asp:XmlDataSource id="ds1" runat="server" DataFile="employees.xml"
/>

Now the data can be bound to any control using the new XML data binding statements. This example uses a FormView control, with the DataSourceID attribute set to the ID of the XmlDataSource control so as to link the two controls together. Then, inside the ItemTemplate section, individual controls that generate the output for the FormView control are declared, just as in the earlier examples that used a SqlDataSource control. This time, however, the XPath data binding method is used, because the items in the source data are XML nodes:

<asp:FormView ID="formview1" runat="server" DataSourceID="ds1" AllowPaging="True"> 
  <ItemTemplate>
    ID:<b>
    <asp:Label ID="lblID" Runat="server"
         Text='<%# XPath("@id") %>' /></b><br 
/>
    Name:<b>
    <asp:Label ID="lblName" Runat="server"
         Text='<%# XPath("name") %>' /></b><br 
/>
    Dept:<b>
    <asp:Label ID="lblDept" Runat="server"
         Text='<%# XPath("department") %>' 
/></b><br />
    Phone:<b>
    <asp:Label ID="lblPhone" Runat="server"
         Text='<%# XPath("phone") %>' /></b>
  </ItemTemplate>
</asp:FormView>

Each Label control in the ItemTemplate of the FormView control is bound to one of the nodes in the source data. The nature of the XML file means that the <employee> element is the one that is repeated within the FormView control (in other words, it is the equivalent of the "rows" in relational data terms). So the Label controls that display the name, department and phone number can be bound directly to the child elements within each <employee> element by using the element name in the XPath method. The ID of each employee is stored in an attribute of that <employee> element, and so in this case the attribute name is used in the XPath method, as XPath("@attribute-name").

The screenshot below shows the results. This example, xpath-xmldatasource.aspx, is included in the samples you can download for this article from http://www.daveandal.net/articles/databinding-syntax/.

Figure 4

Using the XPathSelect Method

The XPath method shown in the previous example returns a single value based on the XPath provided as a parameter. The XPathSelect method uses an XPath expression to return a collection of nodes from an XML document. To demonstrate the XPathSelect method, you use a more complex XML file as the data source. You can see that it contains a second level of nested elements in the form of multiple phone numbers for each employee:


<?xml version="1.0" ?>
<employee-list>
  <employee id="1437">
    <name>Mike</name>
    <department>Sales</department>
    <phone-list>
      <phone>3867</phone>
      <phone>773-6482</phone>
      <phone>(278) 555-3678</phone>
      <phone>(643) 555-1101</phone>
    </phone-list>
  </employee>
  <employee id="7290">
    <name>Nikita</name>
    <department>Marketing</department>
    <phone-list>
      <phone>1442</phone>
      <phone>(278) 555-8521</phone>
      <phone>(532) 555-4444</phone>
    </phone-list>
  </employee>
  ... more employees here ...
</employee-list>

An XmlDataSource control is used to expose this data for data binding, in exactly the same way as the previous example. However, the XPathSelect method can now be used to get a collection of phone numbers for each employee. In the next listing, the first section of the ItemTemplate is the same as in the previous example.

<asp:FormView ID="formview1" runat="server" DataSourceID="ds1" AllowPaging="True">
  <ItemTemplate>
    ID:<b>
    <asp:Label ID="lblID" Runat="server"
         Text='<%# XPath("@id") %>' /></b><br 
/>
    Name:<b>
    <asp:Label ID="lblName" Runat="server"
         Text='<%# XPath("name") %>' /></b><br 
/>
    Dept:<b>
    <asp:Label ID="lblDept" Runat="server"
         Text='<%# XPath("department") %>' 
/></b><br />

    Phone Numbers:<br />
    <asp:Repeater DataSource='<%# XPathSelect("phone-list/phone") 
%>' runat="server">
      <ItemTemplate>
        * <asp:Label ID="lblPhone" runat="server"
               Text='<%# XPath(".") %>' /><br />
      </ItemTemplate>
    </asp:Repeater>    

  </ItemTemplate>
</asp:FormView>

The difference is in the addition of a Repeater control to display the list of phone numbers for each employee. The XPathSelect method is used to set the DataSource for the Repeater to a collection of the elements containing the phone numbers. The XPath "phone-list/phone" selects all the <phone> elements that are children of the current <phone-list> element (the one within the current <employee> element). Then, inside the Repeater control, the value of each <phone> element is displayed in a Label control. The XPath ".", which used to set the Text attribute of the Label control, simply returns the value of the current element.

The screenshot below shows the results. This example, xpathselect-xmldatasource.aspx, is included in the samples you can download for this article from http://www.daveandal.net/articles/databinding-syntax/.

Figure 5

Summary

This article focuses on the new and improved syntax for data binding in ASP.NET 2.0, using the new data source controls and both the new and existing controls for displaying data in "list" or "grid" format. The aim is to explain and demonstrate the uses of the new data binding syntax, rather than how the data source and display controls themselves work. But, as you have seen, the combination of all three technologies - data binding, data source controls and the new list and grid controls - makes it easy to create attractive pages for displaying data with very little effort.

In summary, there are three types of data binding statement you can use in ASP.NET 2.0. For rowset data (i.e. data that is in row and column format) you can use the existing v1.x syntax, or the simplified Eval syntax, to bind to a data column. And, as in v1.x, you can also use these statements to bind to the property of another control, or to the results of an expression:


<%# Container.DataItem("[column-name|property|field]") %>
<%# DataBinder.Eval("[column-name|property|field]"[, "format"]) %>
<%# Eval("[column-name|property|field]"[, "format"]) %>

When using the new GridView, DetailsView or FormView controls, where you implement automatic updates to the data source and use templates to display the data, you must use the new Bind method for any controls containing values that are used as parameters in the SQL INSERT, UPDATE and DELETE statements:

<%# Bind("column-name"[, "format"]) %>

When the source data is XML, rather than a rowset, you must use the XPath or XPathSelect method in the data binding statements. Both of these methods accept an XPath expression that identifies the node or nodes to select. The XPath method returns a value from a single node (attribute or element), while the XPathSelect method returns a collection (as an ArrayList) of values from multiple matching nodes:

<%# XPath("xpath-expression"[, "format"]) %>
<%# XPathSelect("xpath-expression") %>

With all this choice in data binding capabilities, you'll never again have to write code that iterates through your data to build up an HTML table!

About the Author

Alex Homer began his love-hate relationship with computers in 1980 with the Altair and Sinclair Z80. Since 1994 he has been working with and writing about various programming technologies - from databases to building Help systems. However with the growth of the Web, and particularly as ASP rapidly become a viable application platform, he concentrated almost entirely on this topic. Alex has written or contributed to more than 30 books on Web development topics for the major publishers, as well as producing articles for ASPToday, DevX and other sites. He is an MVP and a member of the INETA speaker's bureau, and speaks regularly on a range of Web development topics at conferences such as Microsoft PDC, Tech-Ed, ASP Connections, WebDevCon and VS.NET Live. In what spare time is left, he runs his own software and consultancy company Stonebroom Limited.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值