1. Trang chủ
  2. » Công Nghệ Thông Tin

Pro Server Controls and AJAX Components phần 2 pptx

77 430 0

Đ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

Thông tin cơ bản

Định dạng
Số trang 77
Dung lượng 3,32 MB

Nội dung

52 CHAPTER 2 ■ ENCAPSULATING FUNCTIONALITY IN ASP.NET Next, add the assembly to a test web application by right-clicking the application, selecting Add Reference, and browsing to the user control assembly. The next step is to make the server control available on a web form by registering it: <%@ Register TagPrefix="apressuc" Namespace="ControlsBook2" Assembly="App_Web_simpleusercontrol.ascx.5b4d926a.dll" %> The final step is to add a tag to the .aspx page: <apressUC:SimpleUserControl ID="SimpleUserControl1" runat="server" /> While it is possible to deploy a user control in a similar manner to a custom server control as shown in the preceding example, deployment of a user control as an .ascx file is a bit more straightforward and probably more applicable where user controls are of most interest, which is for sharing code internal to an organization. The design-time rendering of user controls and the ability to deploy a user control as an assembly are welcome ASP.NET improvements; custom server controls provide superior design- time capabilities, simpler deployment, and finer control over functionality. Naturally, all the benefits of custom controls do not come for free. Generally, custom controls require a longer development cycle and a higher skill level from the development staff. The focus of this book is on custom server control development with the goal of easing the learning curve and developing some useful server control samples to help you get started. Building a User Control So far, we’ve discussed user controls and custom server controls, and their benefits and differ- ences. User controls and server controls have differing strengths and trade-offs that we highlight in this section by building two families of controls: • A static hyperlink menu control • A dynamically generated HTML table control The example controls we present may seem simple and somewhat removed from real-world web projects, but we do this for a reason. We believe that you must start simple and build toward more complexity to achieve a deep understanding of the process. In upcoming chapters, we explore controls that leverage the complete functionality available to controls in ASP.NET as well as provide interesting capabilities. ASP.NET developers typically look to the user control as the first option for creating controls due to its ease of construction and simplicity. Building a user control closely mirrors the construc- tion techniques and technical details of a web form. User controls support drag-and-drop development with the Visual Studio control toolbox, a fully editable design surface in the IDE, and a code-behind class file structure to support a separation of UI and logic programming. User controls are built in two ways: • From scratch • By taking out reusable content from an existing web form The first method is used when enough planning and design work is done ahead of time to figure out which portions of the UI are going to be reused on the web site. The second technique Cameron_865-2C02.fm Page 52 Wednesday, February 20, 2008 4:31 PM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com CHAPTER 2 ■ ENCAPSULATING FUNCTIONALITY IN ASP.NET 53 results from refactoring the content of a site after it has been built to make it modular and easier to maintain. The MenuUserControl User Control Our first example takes advantage of the declarative nature of the user control to encapsulate a simple hyperlink menu as a control that we build from scratch. The control is pure, static HTML without a single embedded server control. It consists of nothing more than a list of fixed hyper- links to a variety of web sites. The simplicity is shown in the tags present in the .ascx file in Listing 2-5. The code-behind class in Listing 2-6 is left unchanged from the blank template Visual Studio produces when you add a user control to a web application. Listing 2-5. The MenuUserControl User Control .ascx File <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MenuUserControl.ascx.cs" Inherits="ControlsBook2Web.Ch02.MenuUserControl" %> <div> <span><a href="http://www.apress.com">Apress</a></span> | <span> <a href="http://www.microsoft.com"> Microsoft</a></span> | <span><a href="http://msdn.microsoft.com">MSDN</a></span> | <span><a href="http://asp.net">ASP.NET</a></span> </div> Listing 2-6. The MenuUserControl User Control Code-Behind Class File using System; namespace ControlsBook2Web.Ch02 { public partial class MenuUserControl : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { } } } The Control directive at the top of the user control .ascx file shown in Listing 2-5 identifies it as a user control to the ASP.NET parsing engine. The format is similar to that of the Page directive in an .aspx page file. The Control directive helps set up the code-behind system through its CodeFile and Inherits properties. In ASP.NET 1.1, the attribute name was CodeBehind, but in ASP.NET 2.0 and later, the attribute is CodeFile. The CodeFile attribute points to the location of the class file, and the Inherits attribute specifies the class name the .ascx tag page inherits from. The CodeFile attribute for the @Control (and the @Page) directive in conjunction with the partial class declaration in Cameron_865-2C02.fm Page 53 Wednesday, February 20, 2008 4:31 PM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 54 CHAPTER 2 ■ ENCAPSULATING FUNCTIONALITY IN ASP.NET the code-behind file is part of the new code-behind model in ASP.NET 2.0 and later. The model also removes the requirement to have protected declarations of all server controls used on a web form or user control page in the code behind file, removing what was a fragile relationship in ASP.NET 1.1 between the .aspx/.ascx page and the code-behind file, as well as generally making the code-behind files cleaner and shorter. ■Note The partial class model applies only if the CodeFile attribute exists in the @Page or @Control directive. If the Inherits or src attribute is used without the CodeFile attribute, ASP.NET 2.0 and later resorts to ASP.NET 1.1 code-behind style and places the class as the sole base class for the .aspx or .ascx file. If there isn’t a code-behind file, class generation is also similar to ASP.NET 1.1. Features like strongly typed master page access and previous page access are dependent on the new partial class/code-behind model in ASP.NET 2.0 and later. Notice that the inheritance tree in an .ascx file uses the System.Web.UI.UserControl class instead of the System.Web.UI.Page base class (as in an .aspx file). Using the MenuUserControl User Control To actually see the content of the user control, we must host the user control on a web form. Doing so requires a registration step to give the web form enough information to find the user control content and bring it into the scope of the page via a tag associated with the user control. The menu user control demonstration web form accomplishes this task. Figure 2-3 shows the final output of the web form in the browser. Figure 2-3. The browser view of the HTML output from the menu user control demonstration web form Listing 2-7 shows the source code for the MenuUserControlDemo .aspx file. Cameron_865-2C02.fm Page 54 Wednesday, February 20, 2008 4:31 PM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com CHAPTER 2 ■ ENCAPSULATING FUNCTIONALITY IN ASP.NET 55 Listing 2-7. The MenuUserControlDemo Web Form .aspx File <%@ Page Language="C#" MasterPageFile="~/MasterPage/ControlsBook2MasterPage.Master" AutoEventWireup="true" CodeBehind="MenuUserControlDemo.aspx.cs" Inherits="ControlsBook2Web.Ch02.MenuUserControlDemo" Title="Menu User Control Demo" %> <%@ Register Src="MenuUserControl.ascx" TagName="MenuUserControl" TagPrefix="apressuc" %> <asp:Content ID="Content1" ContentPlaceHolderID="ChapterNumAndTitle" runat="server"> <asp:Label ID="ChapterNumberLabel" runat="server" Width="14px">2</asp:Label>&nbsp;&nbsp;<asp:Label ID="ChapterTitleLabel" runat="server" Width="360px"> Encapsulating Functionality in ASP.NET</asp:Label> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="PrimaryContent" runat="server"> <apressuc:MenuUserControl ID="MenuUserControl1" runat="server" /> </asp:Content> The Register directive does its part by locating the .ascx file representing the user control with its src attribute and determining its look on the page with the TagName and TagPrefix attributes: <%@ Register Src="MenuUserControl.ascx" TagName="MenuUserControl" TagPrefix="apressuc" %> As a common convention in this book, we use apressuc as the tag prefix for our user controls and apress for custom controls. You are free to choose a prefix to suit your organizational or company standards. In the example, we use MenuUserControl as the name of the tag and identify our single instance with the id attribute menu1. The runat="server" attribute is also present to signify that it is a server control and must be handled appropriately by the ASP.NET parsing system: <apressuc:MenuUserControl id="menu1" runat="server" /> An interesting thing to note about this example is how the user control displays on the web form when you view the hosting web form in Design view. It is shown as a gray box that provides little feedback as to what the final output in the browser will be. The TableUserControl User Control Our second user control example raises the degree of difficulty by demonstrating how to use the dynamic control-building features of ASP.NET inside a user control. Because the UserControl class itself has an inheritance chain back to the root System.Web.UI.Control class and is a full- blown control in its own right, we can add controls to its Controls collection at runtime to build up its content structure. We can also manipulate the child controls on its surface programmatically. This example has similar functionality to the examples in Chapter 1. Here, the action is orchestrated according to the properties that the control exposes to the web form at runtime in its declaration, specifically the X and Y properties. Listing 2-8 shows the source code for the TableUserControlascx file. Listing 2-9 shows the source code for the TableUserControl code- behind class file. Cameron_865-2C02.fm Page 55 Wednesday, February 20, 2008 4:31 PM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 56 CHAPTER 2 ■ ENCAPSULATING FUNCTIONALITY IN ASP.NET Listing 2-8. The TableUserControl User Control .ascx File <%@ Control Language="C#" AutoEventWireup="true" CodeBehind= "TableUserControl.ascx.cs" Inherits="ControlsBook2Web.Ch02.TableUserControl" %> <h3> TableUserControl<br /> X:<asp:Label ID="XLabel" runat="server"></asp:Label> Y:<asp:Label ID="YLabel" runat="server"></asp:Label> </h3> <table id="Table1" border="1" runat="server"> </table> Listing 2-9. The TableUserControl User Control Code-Behind Class File using System; using System.Web.UI.HtmlControls; namespace ControlsBook2Web.Ch02 { public partial class TableUserControl : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { XLabel.Text = X.ToString(); YLabel.Text = Y.ToString(); BuildTable(X, Y); } // properties to access dimensions of HTML table public int X {get; set;} public int Y {get; set;} // HTML table building routine private void BuildTable(int xDim, int yDim) { HtmlTableRow row; HtmlTableCell cell; HtmlGenericControl content; for (int y = 0; y < yDim; y++) { // create <TR> row = new HtmlTableRow(); Cameron_865-2C02.fm Page 56 Wednesday, February 20, 2008 4:31 PM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com CHAPTER 2 ■ ENCAPSULATING FUNCTIONALITY IN ASP.NET 57 for (int x = 0; x < xDim; x++) { // create <TD cellspacing=1> cell = new HtmlTableCell(); cell.Attributes.Add("border", "1"); // create a <SPAN> content = new HtmlGenericControl("SPAN"); content.InnerHtml = "X:" + x.ToString() + "Y:" + y.ToString(); cell.Controls.Add(content); row.Cells.Add(cell); } Table1.Rows.Add(row); } } } } In this example, the .ascx page is a mix of HTML content and server controls. The two Label controls come from the System.Web.UI.WebControls namespace. The labels display the X and Y properties’ configuration of the user control: X:<asp:label id="XLabel" Runat="server"></asp:label>; Y:<asp:label id="YLabel" Runat="server"></asp:label> The HtmlTable control comes from the System.Web.UI.HtmlControls namespace and is declared as a table with a border size of 1 on the .ascx page. The table control in the HtmlControl namespace was chosen over the table in the WebControl namespace, because it does not automatically add styling information to the final output. This is desirable at this point in the book; we defer the control styling discussion until Chapter 4. The code-behind class file of the user control is much more interesting in this example, because it contains the content-building code. The X and Y properties exposed by the user control map to private variables in a demonstration of data encapsulation. These properties are exposed to the containing web forms in their .aspx page file via attributes on the user control tag or program- matically in the code-behind class file via a variable reference to an instance of the user control. We could have exposed public methods, fields, and events from the user control as well. The Page_Load() method that is mapped to the web form’s Page.Load event is responsible for transferring the data from the dimension properties to build the table hierarchy via the BuildTable() routine. It also configures the display of the Label controls on the user control to indicate what data was passed in to build the table. We pass on examining the BuildTable() routine in more detail here, because it is very similar to the HTML table building routine from Chapter 1. Using the TableUserControl User Control Like the menu demonstration, the table user control demonstration web form hosts the user control in order for us to realize its output. The table user control demonstration web form sets Cameron_865-2C02.fm Page 57 Wednesday, February 20, 2008 4:31 PM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 58 CHAPTER 2 ■ ENCAPSULATING FUNCTIONALITY IN ASP.NET the X and Y properties of the TableUserControl control in both the .aspx tag page and the code- behind class file. This demonstrates how you can work with the user control in a declarative and a programmatic fashion on a web form. Figure 2-4 shows the table user control demon- stration web form at design time, and Figure 2-5 shows our web form at runtime. Figure 2-4. The Visual Studio Design view of the table user control demonstration web form Figure 2-5. The browser view of the HTML output from the table user control demonstration web form Cameron_865-2C02.fm Page 58 Wednesday, February 20, 2008 4:31 PM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com CHAPTER 2 ■ ENCAPSULATING FUNCTIONALITY IN ASP.NET 59 Listings 2-10 and 2-11 show TableUserControlDemo’s .aspx page file and its code-behind class file, respectively. Listing 2-10. The TableUserControlDemo Web Form .aspx File <%@ Page Language="C#" MasterPageFile="~/MasterPage/ControlsBook2MasterPage.Master" AutoEventWireup="true" CodeBehind="TableUserControlDemo.aspx.cs" Inherits="ControlsBook2Web.Ch02.TableUserControlDemo" Title="Table User Control Demo" %> <%@ Register Src="TableUserControl.ascx" TagName="TableUserControl" TagPrefix="apressuc" %> <asp:Content ID="Content1" ContentPlaceHolderID="ChapterNumAndTitle" runat="server"> <asp:Label ID="ChapterNumberLabel" runat="server" Width="14px">2</asp:Label>&nbsp;&nbsp;<asp:Label ID="ChapterTitleLabel" runat="server" Width="360px"> Encapsulating Functionality in ASP.NET</asp:Label> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="PrimaryContent" runat="server"> <h3> Table User Control</h3> <p> <apressuc:TableUserControl ID="TableUserControl1" runat="server" X="1" Y="1" /> </asp:Content> Listing 2-11. The TableUserControlDemo Code-Behind Class File using System; namespace ControlsBook2Web.Ch02 { public partial class TableUserControlDemo : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { TableUserControl1.X = 4; TableUserControl1.Y = 3; } } } The user control is registered at the top of the .aspx page and declared via an apressuc tag prefix as before. Although we declare the HTML table structure to be a 1 × 1 grid declaratively in the .aspx page file, the code-behind class file programmatically changes it to 4 × 3. The Page_Load() method is executed after the ASP.NET system has set the value of the control declaratively, so it wins the contest over the value of the X and Y parameters. Cameron_865-2C02.fm Page 59 Wednesday, February 20, 2008 4:31 PM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 60 CHAPTER 2 ■ ENCAPSULATING FUNCTIONALITY IN ASP.NET Unlike in ASP.NET 1.1, we did not need to declare a member variable with the name and type of our user control to gain access to the user control in the code-behind class file and programmatically set the parameters. In ASP.NET 1.1, we would have had to add a protected member in the code behind page, like in the following code, but this additional typing is no longer required in the ASP.NET 2.0 and later code-behind model: protected ControlsBook2Web.Ch02.TableUserControl TableUserControl1; After this chapter, we do not touch on building user controls, as this book focuses on building custom server controls. For more information on building ASP.NET user controls, please refer to the ASP.NET documentation. Building a Custom Control We now turn our attention to creating custom server controls. The first decision that we must make when building a custom server control is what base class to inherit from. In the next section, we cover the generic base classes that are available to inherit from in addition to some decision-making guidelines on which base class to use. Which Base Class? The discussion of the control hierarchy in Chapter 1covered the various families of controls in the three main namespaces: System.Web.UI, System.Web.UI.WebControls, and System.Web.UI. HtmlControls. You have the option to inherit from any of the controls in these namespaces. For those who prefer to start with a blank slate, which is the approach we take in this section, three control classes stand out as a potential starting point: • System.Web.UI.Control is the base class that all controls directly or indirectly inherit from. It provides the bare minimum features required to call a class a server control. • System.Web.UI.WebControls.WebControl adds CSS styling management to the rendering process, which makes it easier to build a styled custom control. • System.Web.UI.WebControls.WebParts adds web part functionality to ASP.NET 2.0 and later, whereas with ASP.NET 1.1 web part functionality was only available within the SharePoint runtime environment. It is still possible to create SharePoint-specific web parts to take advantage of the features and capabilities available within the SharePoint runtime environment, but it is no longer a requirement with ASP.NET 2.0 and later. Still a blank state but a bit more specific are the following potential base classes that became available in .NET Framework 2.0 and later: • System.Web.UI.WebControls.CompositeControl can serve as a great starting point when building composite controls. It also removes the need to create a custom designer for composite controls to render correctly at design-time as was required in .NET Framework 1.1. • System.Web.UI.WebControls.DataBoundControl can serve as a great starting point when building custom server controls that include data binding, since it takes care of much of the data binding plumbing code. DataBoundControl also includes a custom designer that can serve most needs when building a data-bound control. Cameron_865-2C02.fm Page 60 Wednesday, February 20, 2008 4:31 PM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com CHAPTER 2 ■ ENCAPSULATING FUNCTIONALITY IN ASP.NET 61 • System.Web.UI.WebControls.CompositeDataBoundControl can serve as a great starting point when building a custom composite server control that includes data binding, since it also helps to manage the data binding and includes a designer. Except for the composite control TableCompCustomControl, the examples in this chapter inherit from System.Web.UI.Control to keep things as simple as possible and provide you with a foundation in the features of the root control class. In later chapters, we examine the extra features that make System.Web.UI.WebControls.WebControl the best starting point for most projects as well as what is available when inheriting from the System.Web.UI.WebControls.WebParts base class. Another option for building controls is inheriting from existing controls that are available in the framework. An example would be to inherit from the TextBox control and add validation capabilities to ensure that only a phone number is entered into it. You could also take a more complex control, such as the DataGrid, and customize it to your needs. Though we do provide a simple example of inheriting from an existing control, this chapter concentrates on building custom controls from scratch or, more accurately, from the base System.Web.UI.Control class. Rendered or Composite Control? The second major decision in building a custom control concerns the construction technique. The two main options available relate to how a control generates its HTML: • A server control that renders its own HTML • A composite control that relies on its children controls to perform the HTML rendering Figure 2-6 shows these two control options. Figure 2-6. Rendered versus composite custom controls >qppkj 8ejlqppula9oq^iep: Naj`ana`?kjpnkh @]p]Cne` 8p]^ha:***8+p]^ha: Nks 8pn:***8+pn: ?ahh 8p`:***8+p`: H]^ah 8ol]j:***8ol]j: ?ahh 8p`:***8+p`: >qppkj 8ejlqppula9oq^iep: ?kilkoepa?kjpnkh Cameron_865-2C02.fm Page 61 Wednesday, February 20, 2008 4:31 PM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... example to the next level, we added an UpdateProgress server control to provide a visual cue to the end user that work is occurring This is a very important design requirement in building effective AJAX- enabled web applications Listings 2- 21 and 2- 22 contain the HtmlControlsAJAX demonstration aspx and code-behind class files, respectively Listing 2- 21 The HtmlControlsAJAX Web Form aspx File 2   2   . manageable. Listing 2- 12. The MenuCustomControl Class File using System; using System.Web; using System.Web.UI; namespace ControlsBook2Lib.Ch 02 { Cameron_865-2C 02. fm Page 62 Wednesday, February 20 , 20 08 4:31. 8ejlqppula9oq^iep: ?kilkoepa?kjpnkh Cameron_865-2C 02. fm Page 61 Wednesday, February 20 , 20 08 4:31 PM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 62 CHAPTER 2 ■ ENCAPSULATING FUNCTIONALITY IN ASP.NET Rendered controls. curve and developing some useful server control samples to help you get started. Building a User Control So far, we’ve discussed user controls and custom server controls, and their benefits and

Ngày đăng: 12/08/2014, 23:20