Overview of ASP. NET composite controls

Source: Internet
Author: User

Introduction to ASP. NET composite controls

Composite controls are just common ASP. NET controls and are not another type of ASP. NET Server controls to be discussed. In this case, why do we always set aside special chapters in books and documents to discuss composite controls? What are the special features of ASP. NET composite controls?

As the name suggests, a composite control is a control that aggregates multiple other controls on a single top and under a single API. If a custom control consists of a label and a text box, it can be said that the control is a composite control. The word "composite" indicates that the control is essentially composed of other components at runtime. The method set and attribute set exposed by the composite control are common but not mandatory. They are provided by the methods and attributes that constitute the component and some new members are added. Composite controls can also trigger custom events and process events caused by child controls.

Composite controls are not so special in ASP. NET because they may be representative of new types of server controls. More specifically, it is because it is supported by ASP. NET runtime during rendering.

Composite controls are powerful tools that can generate rich and complex components that generate the interaction of Self-active objects rather than the markup output of some string generator objects. A composite control is displayed as a control tree. Each component control has its own lifecycle and events, and all components constitute a new API, and abstract as much as possible as needed.

In this article, I will discuss the internal architecture of composite controls to illustrate the benefits it brings to you in many situations. Next, I will generate a composite list control. Compared with the function set of the control I described in previous articles, this control has a richer set of functions.

What are the key points of ASP. NET composite controls?

Some time ago, I tried to study composite controls in ASP. NET. I learned theoretical and practical knowledge from the MSDN document, and also designed some good controls. However, only when I saw the following example by accident did I really understand the key points and advantages of the composite control ). Imagine the simplest and most common control generated by the combination of two other controls Label and TextBox. The following describes a feasible method for writing this control. We name it LabelTextBox.

 
 
  1. public class LabelTextBox :WebControl, INamingContainer  
  2. {  
  3. public string Text {  
  4. get {  
  5. object o = ViewState["Text"];  
  6. if (o == null)  
  7. return String.Empty;  
  8. return (string) o;  
  9.       }  
  10. set { ViewState["Text"] = value; }  
  11.    }  
  12. public string Title {  
  13. get {  
  14. object o = ViewState["Title"];  
  15. if (o == null)  
  16. return String.Empty;  
  17. return (string) o;  
  18.       }  
  19. set { ViewState["Title"] = value; }  
  20.    }  
  21. protected override void CreateChildControls()  
  22.    {  
  23. Controls.Clear();  
  24. CreateControlHierarchy();  
  25. ClearChildViewState();  
  26.    }  
  27. protected virtual void CreateControlHierarchy()  
  28.    {  
  29. TextBox t = new TextBox();  
  30. Label l = new Label();  
  31. t.Text = Text;  
  32. l.Text = Title;  
  33. Controls.Add(l);  
  34. Controls.Add(t);  
  35.    }  
  36. }  

The control has two common attributes: Text and Title) and a rendering engine. These two attributes are saved in the view State and represent the TextBox and Label content respectively. This control has no replacement method for the Render method, and uses the CreateChildControls replacement method to generate its own tag. I will describe the routine process of the presentation phase immediately. The CreateChildControls code first clears the collection of child controls, and then generates a control tree for the components output by the current control. CreateControlHierarchy is a control-specific method that is not required to be marked as protected or virtual. However, note that most built-in composite controls such as DataGrid only expose the logic used to generate the control tree using a similar virtual method.

The CreateControlHierarchy method instantiate multiple components as needed and then synthesize the final output. After that, the Controls are added to the Controls set of the current control. If you want the output result of the control to be an HTML Table, you can create a Table control and Add rows and cells with their own content. All rows, cells, and controls are the child items of the most external table. In this case, you only need to add the Table control to the Controls collection. In the above Code, Label and TextBox are the direct subitem of the LabelTextBox control and are directly added to the set. The display status and running status of the control are normal.

In terms of performance, creating a transient instance of a control is not as efficient as rendering some plain text. Let's consider an alternative method to write the above controls without the need for child controls. This time let's name it TextBoxLabel.

 
 
  1. public class LabelTextBox :WebControl, INamingContainer  
  2. {  
  3.    :  
  4. protected override void Render(HtmlTextWriter writer)  
  5.    {  
  6. string markup = String.Format(  
  7. "< span>{0}< /span>< input type=text value='{1}'>",  
  8. Title, Text);  
  9. writer.Write(markup);  
  10.    }  
  11. }  

The control has the same Text and Title attributes) and replaces the Render method. As you can see, the implementation process is quite simple and the code runs faster. You can replace the synthetic child control by merging text in the string generator and outputting final markup for the browser. Similarly, the control is in good state. But can we really say that its running status is also good? Figure 1 shows the two widgets running on the example Page.

Figure 1: similar controls using different rendering engines

Enable the tracking function on the page and run it again. When the page is displayed in the browser, scroll down and view the control tree. It will be as follows:

Figure 2: Control tree generated by two controls

ASP. NET composite controls are composed of activity instances of components. When ASP. NET is running, these sub-controls are found and can be directly communicated with them when processing published data. The result is that the sub-control can process the view status and automatically trigger events.

For tag-based Merging controls, the situation is different. As shown in, this control is a basic unit of code with an empty Controls set. If an interactive element text box, button, or drop-down menu is injected into the page, ASP. NET cannot process the send-back data and events without the control.

Try to enter some text in the two text boxes and click the "refresh" button in figure 1 to initiate a resend. The first control is the composite control. The allocated text is correctly retained after the message is sent back. The second control using the Render method will lose New text after sending it back. Why? There are two reasons.

The first reason is that I did not name the <input> tag in the above tag. In this way, its content will not be sent back. Note that the name attribute must be used to name the element. Let's modify the Render method as follows.

 
 
  1. protected override void Render(HtmlTextWriter writer)  
  2. {  
  3. string markup = String.Format(  
  4. "< span>{0}< /span>< input type=text value='{1}' name='{2}'>",  
  5. Title, Text, ClientID);  
  6. writer.Write(markup);  
  7. }  

The <input> element of the injected client page now uses the same ID as the server control. During page sending, a server control that matches the ID of the published field can be found during ASP. NET running. But it does not know how to deal with the control. To apply all client changes to the server control in ASP. NET, the control must implement the IPostBackDataHandler interface.

Composite controls that contain TextBox do not need to worry about sending back, because the embedded control uses ASP. NET to automatically solve this problem. Controls that render TextBox must interact with ASP. NET to ensure that the return value can be correctly processed and events are triggered normally. The following code shows how to extend the TextBoxLabel control so that it fully supports sending back.

 
 
  1. bool LoadPostData(string postDataKey, NameValueCollection postCollection)  
  2. {  
  3. string currentText = Text;  
  4. string postedText = postCollection[postDataKey];  
  5. if (!currentText.Equals(postedText, StringComparison.Ordinal))  
  6.     {  
  7. Text = postedText;  
  8. return true;  
  9.     }  
  10. return false;  
  11. }  
  12. void IPostBackDataHandler.RaisePostDataChangedEvent()  
  13. {  
  14. return;  
  15. }  
  16.  
  1. Analysis on Composite Control Event Processing Based on ASP. NET control development
  2. RenderContents application example of ASP. NET Server Control
  3. Analysis on the use of RenderContents Based on ASP. NET control development
  4. Analysis of ASP. NET custom control attributes
  5. Analysis of compound controls based on ASP. NET control development

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.