In this section, you learn how to build templated databound controls. A databound control can be bound to a DataSource control such as the SqlDataSource or ObjectDataSource controls. The ASP.NET 2.0 Framework provides you with a number of new base classes that you can use when creating a custom databound control. Creating a databound control using the previous version of the Framework was not a trivial matter (it took longer than a single afternoon). The ASP.NET 2.0 Framework, on the other hand, makes creating databound controls easy. (You can implement a custom databound control in less than 15 minutes.) So, let's look at some tables and figures. Table 33.1 lists the base control classes for all the standard ASP.NET databound controls. Figure 33.4 displays the inheritance hierarchy of all the new databound controls in the ASP.NET 2.0 Framework. Typically, you'll inherit from one of the leaf nodes. You'll create a control that derives from the base CompositeDataBoundControl, HierarchicalDataBoundControl, or ListControl class.
Figure 33.4. Databound control inheritance hierarchy.This chapter concentrates on inheriting new controls from the base CompositeDataBoundControl class. This is the appropriate base class to use when you want to display one or more database records and use templates. Note You learned how to create controls that inherit from the base ListControl class in Chapter 10, "Using List Controls." Creating a DivView ControlLet's start simple. In this section, we create a custom databound control named the DivView control. The DivView control displays a set of data items (database records) in HTML <div> tags. The DivView control inherits from the base CompositeDataBoundControl class and overrides a single method of the base class. The DivView control overrides the base class's CreateChildControls() method. The DivView control is contained in Listing 33.9. Listing 33.9. DivView.vb
The DivView control supports an ItemTemplate that is used to format each of its data items. You are required to supply an ItemTemplate when you use the DivView control. All the work happens in the CreateChildControls() method. Notice that this is not the same CreateChildControls() method that is included in the base System.Web.UI.Control class. The DivView control overrides the CompositeDataBounControl's CreateChildControls() method. The CreateChildControls() method accepts the following two parameters:
The CreateChildControls() method is called every time that the DivView control renders its data items. When the control is first bound to a DataSource control, the dataSource parameter represents the data items retrieved from the DataSource control. After a postback, the dataSource parameter contains a collection of null values, but the correct number of null values. After a postback, the contents of the data items can be retrieved from View State. As long as the correct number of child controls is created, the Framework can rebuild the contents of the databound control. You can use the dataBinding parameter to determine whether the data items from the data source actually represent anything. Typically, the dataBinding parameter has the value TRue when the page first loads, and the value False after each postback. Notice that the DataBind() method is called after the child controls are created. You must call the DataBind() method when a template includes databinding expressions. Otherwise, the databinding expressions are never evaluated. The page in Listing 33.10 illustrates how you can bind the DivView control to a SqlDataSource control. Listing 33.10. ShowDivView.aspx
In Listing 33.10, the SqlDataSource control represents the Movies database table. The DivView control includes an EditItemTemplate that formats each of the columns from this database table (see Figure 33.5). Figure 33.5. Displaying database records with the DivView control.Creating an AjaxDivView ControlTwo of the three ASP.NET controls that derive from the CompositeDataBoundControl class take advantage of AJAX. The GridView control supports AJAX when sorting and paging through database records. The DetailsView control supports AJAX when paging through database records. There is a good reason for supporting AJAX when building databound controls. Using AJAX can significantly improve your application's performance. By taking advantage of AJAX, you can avoid re-creating an entire page each and every time you perform a database operation. AJAX enables you to transfer only the information you need back and forth between the web server and browser. Note Microsoft insists on using the term Client Callbacks to refer to AJAX. Because AJAX has become the standard name for this technology, I use AJAX instead of Client Callbacks in this book. In this section, we add AJAX functionality to the DivView control. The modified DivView control, the AjaxDivView control, supports having its contents refreshed through an AJAX call. The AjaxDivView control is contained in Listing 33.11. Listing 33.11. AjaxDivView.vb
The AjaxDivView control in Listing 33.11 is very similar to the DivView control created in the previous section, except for the fact that it implements the ICallbackEventHandler interface. This interface has two methods that you must implement: the RaiseCallbackEvent() and GetCallbackResult() methods. The AjaxDivView control calls its DataBind() method in the RaiseCallbackEvent() method. When an AJAX call is made to this control, the control automatically refreshes its contents by rebinding to its data source. The GetCallbackResult() returns a string that is sent to the browser as a result of an AJAX call. The AjaxDivView control renders its contents to a string and sends the string to the browser. Notice that the AjaxDivView control registers two JavaScript scripts in its OnPreRender() method. First, the method registers an external JavaScript library named AjaxDivView.js. Second, it creates a JavaScipt function named AjaxDivView_Refresh() that refreshes the contents of the AjaxDivView. The AjaxDivView.js file is contained in Listing 33.12. Listing 33.12. AjaxDivView.js
The JavaScript file in Listing 33.12 includes two functions. The first function, named AjaxDivView_Result(), is called after AjaxDivView content is retrieved from the server. This function updates the innerHTML of the AjaxDivView control's containing <div> tag with the updated content. The second function, the AjaxDivView_Error() function, is called only when there is an error on the server during an AJAX call. This function simply displays the error in a JavaScript alert box. The page in Listing 33.13 illustrates how you can use the AjaxDivView control. Listing 33.13. ShowAjaxDivView.aspx
The page in Listing 33.13 displays the contents of the Movies database table. The AjaxDivView control is bound to a SqlDataSource control. The page includes a little bit of JavaScript. The JavaScript causes the contents of the AjaxDivView to refresh automatically every five seconds. If you change one of the records in the Movies database table, then the contents of the AjaxDivView control automatically updates to reflect the change within five seconds (see Figure 33.6). Figure 33.6. Displaying data with the AjaxDivView control.The following JavaScript statement causes the AjaxDivView to update its contents every five seconds: window.setInterval("AjaxDivView_Refresh()", 5000); The AjaxDivView_Refresh() method initiates the AJAX call to refresh the AjaxDivView control's contents. As an alternative to waiting the five seconds after a database update, if you are really impatient, you can click the button contained on the page. The button is a client-side button that calls the AjaxDivView_Refresh() method in its onclick handler. Notice that the current time is displayed at the top of the page. This time never changes even when the contents of the AjaxDivView is updated. Only the AjaxDivView is refreshed, and not the rest of the page. Creating an AjaxFormView ControlIn this section, we create an AjaxFormView control. The AjaxFormView control works like the standard ASP.NET FormView control. However, the AjaxFormView control enables you to update and delete database records from the client by making AJAX calls back to the server. Unfortunately, the code for the AjaxFormView control is too long to include in the pages of this book. The entire source code for the control is included on the CD that accompanies this book in both VB.NET and C# versions. The AjaxFormView control has the following properties:
The AjaxFormView control can be used to either insert or update a database record. You can set the control to either Insert or Update mode by setting the DefaultMode property. Warning Make sure that you assign a value to the AjaxFormView control's DataKeyNames property when the control is set to Edit mode. When you set the AjaxFormView control to Insert mode, the control renders an Insert button with its RenderInsertButton() method. This method creates a client-side button that initiates an AJAX call. The code for the RenderInsertButton() method is contained in Listing 33.14. Listing 33.14. RenderInsertButton()
The RenderInsertButton() method creates a button onclick handler that performs three actions. First, it sets the __theFormPostData variable to an empty string. Next, it calls the WebForm_InitCallback() method. These first two steps are required to pass the updated form field values back to the server in the AJAX call. By default, when an AJAX call is made back to the server, only the initial values of all the form fields are sent with the AJAX request. Finally, the onclick handler actually makes the AJAX call. The necessary function call to initiate the AJAX request is retrieved with the help of the Page.ClientScript.GetCallbackEventReference() method. When a user clicks the Insert button, an AJAX call is made back to the server and the control's RaiseCallbackEvent() method executes. When the Insert button is clicked, this method calls the HandleInsert() method. The code for the HandleInsert() method is contained in Listing 33.15. Listing 33.15. HandleInsert()
The HandleInsert() method gets the values of the databinding expressions from the InsertItemTemplate by calling the template's ExtractValues() method. This method is available because the InsertItemTemplate is marked as a template that supports two-way databinding. The DataSource control to which the AjaxFormView control is bound has a DataSourceView associated with it. This DataSourceView is retrieved by a call to the GeTData() method. The DataSourceView class includes Insert(), Update(), and Delete() methods you can call to modify the database data associated with the FormView. The HandleInsert() method in Listing 33.15 calls the Insert() method to insert a new database record. The page in Listing 33.16 illustrates how you can use the AjaxFormView control. This page contains three controls: an AjaxFormView, AjaxDivView, and SqlDataSource control. The page enables you to add new records to the Movies database table (see Figure 33.7). Figure 33.7. Inserting new records with the AjaxFormView control.Listing 33.16. ShowAjaxFormView.aspx
When you add new records to the Movies database table by clicking the AjaxFormView control's Insert button, the page is not posted back to the server. Instead, the new record is added to the database with an AJAX call. The AjaxDivView displays the current contents of the Movies database table. The contents of the AjaxDivView control are refreshed automatically whenever a new record is added with the AjaxFormView control. The AjaxDivView control is refreshed by the AjaxFormView control's client-side ItemInserted() method. The beautiful thing about both the AjaxFormView and AjaxDivView control is that both controls enable you to interact with the web server without posting the page that contains the controls back to the web server. This creates a user experience much closer to working with a desktop application. It also greatly improves the performance of your application because the entire page does not need to be re-created each and every time that you need to perform a database operation. |