ASP.NET AJAX Programmer’s Reference - Chapter 20 pps

54 290 0
ASP.NET AJAX Programmer’s Reference - Chapter 20 pps

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Using UpdatePanel in User Controls and Custom Controls The previous chapter developed two partial-rendering-enabled custom controls named BaseMasterDetailControl and BaseMasterDetailControl2 , which I will use in this chapter to develop partial-rendering-enabled custom server controls. I’ll then use examples to show you how to use ASP.NET AJAX partial page rendering in your own Web applications. MasterDetailControl MasterDetailControl is a server control that inherits from BaseMasterDetailControl2 and extends its functionality to use the ASP.NET GridView as a master server control, as shown in Listing 20-1 . Listing 20-1: The MasterDetailControl Server Control using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Collections; using System.Drawing; using System.ComponentModel; (continued) c20.indd 911c20.indd 911 8/20/07 8:34:10 PM8/20/07 8:34:10 PM Chapter 20: Using UpdatePanel in User Controls and Custom Controls 912 Listing 20-1 (continued) namespace CustomComponents { public class MasterDetailControl : BaseMasterDetailControl2 { protected override BaseDataBoundControl CreateBaseDataBoundControlMaster() { GridView master = new GridView(); master.AllowPaging = true; master.AllowSorting = true; master.AutoGenerateColumns = true; master.AutoGenerateSelectButton = true; master.ID = “MasterGridView”; return master; } protected override void RegisterMasterEventHandlers() { ((GridView)Master).SelectedIndexChanged += new EventHandler(Master_SelectedIndexChanged); ((GridView)Master).PageIndexChanged += new EventHandler(Master_ResetSelectedValue); ((GridView)Master).Sorted += new EventHandler(Master_ResetSelectedValue); } public int PageSize { get { EnsureChildControls(); return ((GridView)Master).PageSize; } set { EnsureChildControls(); ((GridView)Master).PageSize = value; } } [TypeConverter(typeof(StringArrayConverter))] public string[] DataKeyNames { get { EnsureChildControls(); return ((GridView)Master).DataKeyNames; } set c20.indd 912c20.indd 912 8/20/07 8:34:11 PM8/20/07 8:34:11 PM Chapter 20: Using UpdatePanel in User Controls and Custom Controls 913 { EnsureChildControls(); ((GridView)Master).DataKeyNames = value; ((DetailsView)Detail).DataKeyNames = value; } } protected override void Master_DataBound(object sender, EventArgs e) { for (int i = 0; i < ((GridView)Master).Rows.Count; i++) { if (((GridView)Master).DataKeys[i].Value == this.SelectedValue) { ((GridView)Master).SelectedIndex = i; break; } } Master_SelectedIndexChanged(null, null); } void Master_ResetSelectedValue(object sender, EventArgs e) { if (((GridView)Master).SelectedIndex != -1) { ((GridView)Master).SelectedIndex = -1; Master_SelectedIndexChanged(null, null); } } protected virtual void Master_SelectedIndexChanged(object sender, EventArgs e) { if (((GridView)Master).SelectedIndex == -1) this.Detail.Visible = false; else this.Detail.Visible = true; this.SelectedValue = ((GridView)Master).SelectedValue; UpdateDetail(sender, e); } } } I’ll discuss the methods and properties of the MasterDetailControl server control in the following sections. CreateBaseDataBoundControlMaster As Listing 20-1 shows, the MasterDetailControl server control overrides the CreateBaseDataBoundControlMaster method of its base class to create and return a GridView server control as the master server control. As you can see, this method instantiates a GridView server control and sets its AllowPaging , AllowSorting , AutoGenerateColumns , and AutoGenerateSelectButton properties. c20.indd 913c20.indd 913 8/20/07 8:34:11 PM8/20/07 8:34:11 PM Chapter 20: Using UpdatePanel in User Controls and Custom Controls 914 RegisterMasterEventHandlers The main responsibility of the RegisterMasterEventHandlers method is to register event handlers for those events of the master server control that require the detail server control to update. The GridView server control exposes the following three important events that meet that description, as shown in Listing 20-1 : ❑ SelectedIndexChanged : The GridView server control raises this event when the end user selects a new record from the records that the control is displaying. Since the detail server control displays the details of the selected record, every time a new record is selected — that is, every time the SelectedIndexChanged event is raised — the detail server control must be updated with the details of the newly selected record. Because of this, the MasterDetailControl registers a method named Master_SelectedIndexChanged as an event handler for the SelectedIndexChanged event of the GridView server control: ((GridView)Master).SelectedIndexChanged += new EventHandler(Master_SelectedIndexChanged); ❑ PageIndexChanged : The GridView server control raises this event when the end user clicks an element in the pager user interface to display a new page of records. Since the new page of records may not include the selected record, you need to hide the detail server control until the end user makes a new selection. That is why the MasterDetailControl registers a method named Master_ResetSelectedValue as an event handler for the PageIndexChanged event of the GridView server control: ((GridView)Master).PageIndexChanged += new EventHandler(Master_ResetSelectedValue); ❑ Sorted : The GridView server control raises this event when the end user clicks the header text of a column to sort the displayed records. Again, the newly sorted records may not include the selected record, so you need to hide the detail server control. That is why the MasterDetailControl registers the Master_ResetSelectedValue method as an event handler for the Sorted event of the GridView server control: ((GridView)Master).Sorted += new EventHandler(Master_ResetSelectedValue); Master_SelectedIndexChanged As you can see from Listing 20-1 , this method hides the detail server control if the SelectedIndex property of the master server control is set to -1 — that is, if no record is selected. There is no point in rendering the detail server control if there is no selected record to display: if (((GridView)Master).SelectedIndex == -1) this.Detail.Visible = false; else this.Detail.Visible = true Next, the method stores the value of the SelectedValue of the GridView server control in the SelectedValue property of the MasterDetailControl : this.SelectedValue = ((GridView)Master).SelectedValue; c20.indd 914c20.indd 914 8/20/07 8:34:11 PM8/20/07 8:34:11 PM Chapter 20: Using UpdatePanel in User Controls and Custom Controls 915 The MasterDetailControl inherits the SelectedValue property from the BaseMasterDetailControl . As Listing 20-1 shows, this property stores its value in the view state for future reference. It is necessary to store the selected record in the view state because the following requests may end up rebinding the GridView server control and consequently resetting the SelectedValue property of the control. In such situations, you can retrieve the selected value from the view state and assign it to the SelectedValue property of the GridView server control after rebinding the control if the control still contains the selected record. As Listing 20-1 shows, the Master_SelectedIndexChanged method finally calls the UpdateDetail method to update the detail server control. This is necessary because a new record has been selected. MasterDetailControl inherits the UpdateDetail method from its base class — that is, from the BaseMasterDetailControl . As you can see from Listing 20-1 , this method first calls the DataBind method on the detail server control to rebind the control and consequently to retrieve fresh data from the underlying data store: detail.DataBind(); Next, the method calls the Update method on the detail UpdatePanel server control to force this control to update. Master_ResetSelectedValue As you can see from Listing 20-1 , this method simply sets the SelectedIndex property of the GridView server control to -1 to signal that no record is selected, and then invokes the Master_SelectedIndexChanged method discussed in the previous section. Master_DataBound As you can see from Listing 20-1 , this method first searches through the GridViewRow server controls in the Rows collection of the GridView server control for a GridViewRow server control with the same primary key field value as the one stored in the SelectedValue property. If the search succeeds, the method assigns the index of the GridViewRow server control to the SelectedIndex property of the GridView server control to specify this GridViewRow server control as the selected row: for (int i = 0; i < ((GridView)Master).Rows.Count; i++) { if (((GridView)Master).DataKeys[i].Value == this.SelectedValue) { ((GridView)Master).SelectedIndex = i; break; } } T h e GridView server control uses an instance of a server control named GridViewRow to display each of its data records. The Rows collection property of the GridView server control contains all the GridViewRow server controls that display the data records of the server control. The GridView server control exposes a collection property named DataKeys , which contains one DataKey object for each displayed data record in which the names and values of the primary key datafields of the record are stored. In other words, each DataKey object in the DataKeys collection corresponds to a GridViewRow server control in the Rows collection. c20.indd 915c20.indd 915 8/20/07 8:34:12 PM8/20/07 8:34:12 PM Chapter 20: Using UpdatePanel in User Controls and Custom Controls 916 Next, the method invokes the Master_SelectedIndexChanged method discussed earlier: Master_SelectedIndexChanged(null, null); Properties As you can see from Listing 20-1 , the MasterDetailControl , like any other composite server control, exposes the properties of its child controls as its own top-level properties, as follows: ❑ PageSize : This string property exposes the PageSize property of the GridView server control as top-level property. Recall that the PageSize property of a GridView server control specifies the total number of records to display. ❑ DataKeyNames : This array property exposes the DataKeyNames property of the GridView server control as top-level property. Recall that the DataKeyNames property of a GridView server control contains the list of primary key datafield names. Note that the DataKeyNames property is annotated with the TypeConverter(typeof(StringArray Converter)) metadata attribute to instruct the page parser that it must use the StringArrayConverter to convert the declarative value of the DataKeyNames to the array. This declarative value is the value that the page developer declaratively assigns to the DataKeyNames attribute on the tag that represents the MasterDetailControl server control on an .aspx or .ascx file. This declarative value is a string of comma-separated list of substrings in which each substring contains the name of a primary key datafield name. As the name suggests, the StringArrayConverter converts this string into an array, which the page parser then automatically assigns to the DataKeyNames property of the MasterDetailControl server control. Note that the getters and setters of these properties of the MasterDetailControl invoke the EnsureChildControls method before they attempt to access the associated child server controls, as I mentioned earlier. Using MasterDetailControl in a Web Page Add the following files to the App_Code directory of the application that contains the page that uses the MasterDetailControl control: ❑ BaseMasterDetailControl.cs : Listing 19-12 presents the content of this file. ❑ ContainerType.cs : Listing 19-13 presents the content of this file. ❑ MasterDetailContainer.cs : Listing 19-14 presents the content of this file. ❑ BaseMasterDetailControl2.cs : Listing 19-15 presents the content of this file. ❑ MasterDetailControl.cs : Listing 20-1 presents the content of this file. Listing 20-2 presents a page that uses the MasterDeatilControl . Note that this page uses a theme, a database with two tables named Products and Categories, and a connections string named MyConnectionString. I’ll discuss this theme, database, and connection string shortly. If you run this page, you’ll get the result shown in Figure 20-1 . c20.indd 916c20.indd 916 8/20/07 8:34:12 PM8/20/07 8:34:12 PM Chapter 20: Using UpdatePanel in User Controls and Custom Controls 917 Listing 20-2: A Page that Uses the MasterDetailControl <%@ Page Language=”C#” Theme=”Theme1” %> <%@ Register Namespace=”CustomComponents” TagPrefix=”custom” %> <!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>Untitled Page</title> </head> <body> <form id=”form1” runat=”server”> <asp:ScriptManager ID=”ScriptManager1” runat=”server” /> <custom:MasterDetailControl ID=”MasterDetailControl1” runat=”server” DataKeyNames=”ProductID” DetailDataSourceID=”DetailDataSource” MasterDataSourceID=”MasterDataSource” PageSize=”3” MasterSkinID=”GridView1” DetailSkinID=”DetailsView1” CellSpacing=”20” HorizontalAlign=”Center” GridLines=”both” BorderStyle=”Ridge” BorderWidth=”20” BorderColor=”Yellow” BackImageUrl=”images.jpg”> <MasterContainerStyle HorizontalAlign=”center” BorderStyle=”Ridge” BorderWidth=”20” BorderColor=”Yellow” /> <DetailContainerStyle BorderStyle=”Ridge” BorderWidth=”20” BorderColor=”Yellow” /> </custom:MasterDetailControl> <asp:SqlDataSource runat=”server” ID=”MasterDataSource” ConnectionString=”<%$ ConnectionStrings:MyConnectionString %>” SelectCommand=”Select ProductID, ProductName, UnitPrice From Products” /> <asp:SqlDataSource ID=”DetailDataSource” runat=”server” ConnectionString=”<%$ ConnectionStrings:MyConnectionString %>” SelectCommand=”Select * From Products where ProductID=@ProductID” UpdateCommand=”Update Products Set ProductName=@ProductName, CategoryID=@CategoryID, UnitPrice=@UnitPrice, DistributorName=@DistributorName where ProductID=@ProductID” DeleteCommand=”Delete From Products where ProductID=@ProductID” InsertCommand=”Insert Into Products (ProductName, CategoryID, UnitPrice, DistributorName) Values (@ProductName, @CategoryID, @UnitPrice, @DistributorName)”> <SelectParameters> <asp:ControlParameter ControlID=”MasterDetailControl1” Name=”ProductID” PropertyName=”SelectedValue” DefaultValue=”1” /> </SelectParameters> </asp:SqlDataSource> </form> </body> </html> c20.indd 917c20.indd 917 8/20/07 8:34:12 PM8/20/07 8:34:12 PM Chapter 20: Using UpdatePanel in User Controls and Custom Controls 918 As you can see, the MasterDetailControl displays only the master portion of the control. Now if you select a record from the GridView control, you’ll get the result shown in Figure 20-2 : the DetailsView server control displays the detail of the selected record. Note that the DetailsView server control displays the standard Edit and Delete buttons to enable end users to edit and delete the current record from the underlying data store. The DetailsView server control also contains the New button to enable the end user to add a new record to the data store. Thanks to the ASP.NET AJAX partial page rendering infrastructure, all the user interactions with the GridView and DetailsView server controls are handled asynchronously in the background without interrupting the user or reloading the entire page. Note that the page shown in Listing 20-2 takes advantage of ASP.NET 2.0 themes. A theme is implemented as a subfolder under the App_Themes folder. The subfolder must have the same name as the theme. A theme subfolder consists of one or more skin files and their respective image and Cascading Style Sheet files. Since ASP.NET 2.0 merges all the skin files of a theme into a single skin file, page devel- opers can use as many skin files as necessary to organize the theme folder. Themes are assigned to the containing page, not to the the individual controls. Figure 20-1 c20.indd 918c20.indd 918 8/20/07 8:34:13 PM8/20/07 8:34:13 PM Chapter 20: Using UpdatePanel in User Controls and Custom Controls 919 The @Page directive in ASP.NET 2.0 exposes a new attribute named Theme , which is set to the name of the desired theme. Since all themes are subfolders of the App_Themes folder, the ASP.NET framework knows where to find the assigned theme. A skin file includes one or more control skins. A control skin defines the appearance properties of a class of server controls. The definition of a control skin is very similar to the declaration of an instance of the control on an ASP.NET page. This doesn’t mean that all properties of a server control can be set in its skin. In general, only the appearance properties can be included and set in a control skin. If the SkinID property of a control skin isn’t set, the control skin is treated as the default skin. A default skin is automatically applied to the control instances whose SkinID properties aren’t set. If the SkinID property of a control skin is set, it will be applied only to the control instances whose SkinID property is set to the same value. Figure 20-2 c20.indd 919c20.indd 919 8/20/07 8:34:13 PM8/20/07 8:34:13 PM Chapter 20: Using UpdatePanel in User Controls and Custom Controls 920 The page shown in Listing 20-2 uses a theme named Theme1 that contains a skin file with the following content: <asp:GridView SkinID=”GridView1” runat=”server” BackColor=”LightGoldenrodYellow” BorderColor=”Tan” BorderWidth=”1px” CellPadding=”2” ForeColor=”Black” GridLines=”None”> <FooterStyle BackColor=”Tan” /> <SelectedRowStyle BackColor=”DarkSlateBlue” ForeColor=”GhostWhite” /> <PagerStyle BackColor=”PaleGoldenrod” ForeColor=”DarkSlateBlue” HorizontalAlign=”Center” /> <HeaderStyle BackColor=”Tan” Font-Bold=”True” /> <AlternatingRowStyle BackColor=”PaleGoldenrod” /> </asp:GridView> <asp:DetailsView SkinID=”DetailsView1” runat=”server” Width=”100%” BackColor=”LightGoldenrodYellow” BorderColor=”Tan” BorderWidth=”1px” CellPadding=”2” ForeColor=”Black” GridLines=”None” HorizontalAlign=”Center”> <FooterStyle BackColor=”Tan” /> <EditRowStyle BackColor=”DarkSlateBlue” ForeColor=”GhostWhite” /> <PagerStyle BackColor=”PaleGoldenrod” ForeColor=”DarkSlateBlue” HorizontalAlign=”Center” /> <HeaderStyle BackColor=”Tan” Font-Bold=”True” /> <AlternatingRowStyle BackColor=”PaleGoldenrod” /> </asp:DetailsView> Also note that the page shown in Listing 20-2 connects to a database named ProductsDB that consists of two database tables named Products and Categories . The following table describes the Products database table: The following table describes the Categories database table: Column Name Data Type ProductID int ProductName varchar (50) CategoryID int UnitPrice decimal (18, 0) DistributorName varchar (50) Column Name Data Type CategoryID int CategoryName varchar (50) CategoryDescription varchar (255) DateCreated datetime c20.indd 920c20.indd 920 8/20/07 8:34:13 PM8/20/07 8:34:13 PM [...]... clicks the Reply button, the page shown in Figure 2 0-9 is displayed, which includes the user interface that enables the user to enter the reply to the specified message 945 c20.indd 945 8 /20/ 07 8:34:21 PM Chapter 20: Using UpdatePanel in User Controls and Custom Controls Figure 2 0- 9 Listing 2 0-1 0 presents the implementation of the partial-rendering-enabled threaded discussion forum user control As... Controls and Custom Controls Figure 2 0-6 Note that the DetailsView detail server control contains the standard Edit, Delete, and New buttons to enable the end user to edit an existing category, delete a category, and add a new category If you click the Edit button, you’ll get the result shown in Figure 2 0-7 Figure 2 0- 7 944 c20.indd 944 8 /20/ 07 8:34 :20 PM Chapter 20: Using UpdatePanel in User Controls... you’ll get the result shown in Figure 2 0-5 Now, if you click the Edit link on the fifth row, you’ll get the result shown in Figure 2 0-6 As you can see, the Category cell now contains the MasterDetailControl4 server control, which consists of a DropDownList master server control and a DetailsView detail server control Figure 2 0-5 943 c20.indd 943 8 /20/ 07 8:34 :20 PM Chapter 20: Using UpdatePanel in User Controls... 1 9-1 2 presents the content of this file ❑ ContainerType.cs: Listing 1 9-1 3 presents the content of this file ❑ MasterDetailContainer.cs: Listing 1 9-1 4 presents the content of this file ❑ BaseMasterDetailControl2.cs: Listing 1 9-1 5 presents the content of this file 928 c20.indd 928 8 /20/ 07 8:34:16 PM Chapter 20: Using UpdatePanel in User Controls and Custom Controls ❑ MasterDetailControl.cs: Listing 2 0-1 ... ContainterType.cs: Listing 1 9-1 3 presents the content of this file ❑ MasterDetailContainer.cs: Listing 1 9-1 4 presents the content of this file ❑ BaseMasterDetailControl2.cs: Listing 1 9-1 5 presents the content of this file ❑ MasterDetailControl.cs: Listing 2 0-1 presents the content of this file ❑ MasterDetailControl2.cs: Listing 2 0-3 presents the content of this file ❑ MasterDetailControl4.cs: Listing 2 0-7 presents... Listing 2 0-5 As you can see, MasterDetailControl3 simply overrides the CreateBaseDataBoundControlMaster method that it inherits from MasterDetailControl2 and replaces the DropDownList server control with a ListBox server control Listing 2 0-5 : The MasterDetailControl3 Control using System; using System.Data; using System.Configuration; (continued) 927 c20.indd 927 8 /20/ 07 8:34:15 PM Chapter 20: Using... Listing 2 0-7 presents the content of this file 940 c20.indd 940 8 /20/ 07 8:34:19 PM Chapter 20: Using UpdatePanel in User Controls and Custom Controls ❑ MasterDetailField.cs: Listing 2 0-8 presents the content of this file ❑ Product.cs: The following code listing presents the content of this file (Notice that the ObjectDataSource control shown in Listing 2 0-9 uses the Product class defined in this file.)... com.Parameters.AddWithValue(“@ProductID”, ProductID); con.Open(); com.ExecuteNonQuery(); con.Close(); } } 941 c20.indd 941 8 /20/ 07 8:34:19 PM Chapter 20: Using UpdatePanel in User Controls and Custom Controls Also note that the page shown in Listing 2 0-9 uses the same database (ProductsDB) and connection string as the pages in the previous sections Listing 2 0-9 : Using the MasterDetailField Data Control Field Declaratively . value. Figure 2 0-2 c20.indd 919c20.indd 919 8 /20/ 07 8:34:13 PM8 /20/ 07 8:34:13 PM Chapter 20: Using UpdatePanel in User Controls and Custom Controls 920 The page shown in Listing 2 0-2 uses a theme. controls. Figure 2 0-1 c20.indd 918c20.indd 918 8 /20/ 07 8:34:13 PM8 /20/ 07 8:34:13 PM Chapter 20: Using UpdatePanel in User Controls and Custom Controls 919 The @Page directive in ASP. NET 2.0 exposes. result shown in Figure 2 0-1 . c20.indd 916c20.indd 916 8 /20/ 07 8:34:12 PM8 /20/ 07 8:34:12 PM Chapter 20: Using UpdatePanel in User Controls and Custom Controls 917 Listing 2 0-2 : A Page that Uses

Ngày đăng: 09/08/2014, 06:23

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan