asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search





Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

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


  • email this article to a colleague
  • suggest an article

    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.

    << Introduction

    Rate This Article

  • Supporting Products/Tools
    Proposion N2N
    Proposion N2N connects Microsoft .NET applications to Lotus Notes and Lotus Domino databases. This ADO.NET managed data provider allows you to perform blindingly fast queries and updates of Notes data from ASP.NET pages, .NET web services, Windows, or Mobile applications. An innovative SQL-like query language leverages the unique features of Notes and makes collaborative software accessible to relational database programmers.
    [Top]
    Other Articles
    Sep 15, 2005 - Building an Image Keyword System
    Unlike text-based file formats image files aren't made up of words, which makes searching for an image file by keyword difficult. Instead of being able to simply open the file to see what it contains, we're stuck looking at the text around it and other metadata to determine the image's meaning. In this article, Ziran Sun shows you how to build a simple database-based image keyword system that allows you to associate keywords with images and use these keywords to make finding images easier.
    [Read This Article]  [Top]
    Apr 7, 2005 - A Step-by-Step Guide To Using MySQL with ASP.NET - Part 2
    In the second part of of his article on using MySQL with ASP.NET, Ziran Sun covers how to add a new MySQL user to the database server, assign the user the appropriate permissions, connect to the database, and build a simple ASP.NET page to perform a query.
    [Read This Article]  [Top]
    Feb 10, 2005 - A Step-by-Step Guide To Using MySQL with ASP.NET - Part 1
    Back in the days of classic ASP, if you were building a database-driven web site, your choice was either to invest a lot of money to get a copy of Microsoft SQL Server (or some other enterprise-ready database) or invest a lot of time finding a way to deal with the performance and scalability limitations of Microsoft Access. Luckily these days there's another viable alternative: MySQL.
    [Read This Article]  [Top]
    Jan 27, 2005 - Moving a Database from SQL Server 7.0 to SQL Server 2000
    Moving or copying a SQL Server database from one machine to another requires a lot of preparation in order to ensure a smooth transfer. In this article, Dina Fleet Berry examines the different methods and highlights the different issues associated with each of them.
    [Read This Article]  [Top]
    Jan 6, 2005 - Debugging a SQL Stored Procedure from inside SQL Server 2000 Query Analyzer
    There are many times when using SQL Server 2000 Query Analyzer to debug SQL statements is a better choice than debugging in Visual Studio .NET. In this article, Dina Fleet Berry explains why and walks you through the debugging process step-by step.
    [Read This Article]  [Top]
    Nov 24, 2004 - Persisting .NET Objects to SQL Server Using SQLXML and Serialization
    As a follow up to his article on retrieving objects from SQL Server using SQLXML and serialization, Gianluca Nuzzo discusses saving objects back to SQL Server using a schema definition file and updategrams.
    [Read This Article]  [Top]
    Sep 14, 2004 - Transaction Processing in ADO.NET 2.0
    One area that stands out when comparing ADO.NET 1.x to ADO.NET 2.0 is transaction processing. Bill Ryan shows just how easy transaction processing has become with the TransactionScope object in ADO.NET 2.0.
    [Read This Article]  [Top]
    Sep 8, 2004 - Custom Object Data Binding with .NET
    Developers often use brute force coding to marshal data between the GUI and application objects. In this article, Luther Stanton explains how to use .NET's out-of-the box data-binding functionality to make this job much easier.
    [Read This Article]  [Top]
    Sep 2, 2004 - Queue MSMQ Messages from SQL Server
    Learn how to create a console application to queue a message in Microsoft Message Queuing (MSMQ) and then use an extended stored procedure to call the console application from a SQL Server trigger.
    [Read This Article]  [Top]
    Aug 30, 2004 - Tuning Up ADO.NET Connection Pooling in ASP.NET Applications
    Connection pooling increases the performance of Web applications by reusing active database connections instead of creating a new connection with every request. This article shows how to monitor the connection pool, diagnose a potential problem, and apply the appropriate fix.
    [Read This Article]  [Top]
    Mailing List
    Want to receive email when the next article is published? Just Click Here to sign up.

    Support the Active Server Industry



    JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers