RenderContents application example of ASP. NET Server Control
I believe that when you browse various websites, you will often see similar texts such as "Contact Us. When you click the text, the operating system will automatically open its own mail client software, prompting you to send an email. In this example, a custom Server Control RenderContentsControl is implemented to display hyperlinks containing "mailto: Email Address. Example 1 in this example:
1. the hyperlink text "my email address" is displayed on the page ". When you click the link, the system sends an email to the my@mysample.com ".
Before implementing the above ASP. NET Server control, the control should first be analyzed as follows: This control contains the appearance elements, such as the text size, color, bold or not. Therefore, the Control base class should not inherit from the Control class, but from the WebControl class. In this way, developers do not have to implement these style attributes.
The following lists the source code of the RenderContentsControl. cs file that implements custom server controls.
- UsingSystem;
- UsingSystem. ComponentModel;
- UsingSystem. Security;
- UsingSystem. Security. Permissions;
- UsingSystem. Web;UsingSystem. Web. UI;
- UsingSystem. Web. UI. WebControls;
- NamespaceUsingRenderContentsControl {
- [
- AspNetHostingPermission (SecurityAction. Demand,
- Level = AspNetHostingPermissionLevel. Minimal ),
- AspNetHostingPermission (SecurityAction. InheritanceDemand,
- Level = AspNetHostingPermissionLevel. Minimal ),
- DefaultProperty ("Email"), ParseChildren (True,"Text"),
- ToolboxData ("<{0}: RenderContentsControl runat = server ></{ 0}: RenderContentsControl>")
- ]
-
- Public ClassRenderContentsControl: WebControl {
- // Implement Email attributes
- [Bindable (True)]
- [Category ("Appearance")]
- [DefaultValue ("")] [Localizable (True)]
-
- Public StringEmail
- {
- Get{
- String s = (String) ViewState ["Email"];
- Return(S =Null)? String. Empty: s );
- }
- Set{
- ViewState ["Email"] = Value;
- }
- }
- // Implement the Text attribute
-
- [
- Bindable (True), Category ("Appearance"), DefaultValue (""), Localizable (True),
- PersistenceMode (PersistenceMode. InnerDefaultProperty)
- ]
-
- Public Virtual StringText
- {
- Get{
- StringS = (String) ViewState ["Text"];
- Return(S =Null)? String. Empty: s;
- }
- Set{
- ViewState ["Text"] = Value;
- }
- }
- // Rewrite the TagKey attribute
-
- Protected OverrideHtmlTextWriterTag TagKey
- {
- Get{
- ReturnHtmlTextWriterTag.;
- }
- }
-
- // Override the AddAttributesToRender Method
-
- Protected Override VoidAddAttributesToRender (HtmlTextWriter writer)
- {
- Base. AddAttributesToRender (writer );
- Writer. AddAttribute (HtmlTextWriterAttribute. Href,"Mailto :"+ Email );
- }
-
- // Rewrite the RenderContents Method
-
- Protected Override VoidRenderContents (HtmlTextWriter writer)
- {
- If(Text = String. Empty ){
- Text = Email;
- }
- Writer. WriteEncodedText (Text );
- }
- }
- }
As shown in the above Code, the RenderContentsControl class inherits from the WebControl base class. The reason is described above. In addition, the implementation process of the RenderContentsControl class also includes metadata attribute tag, three attributes Email, Text, and TagKey), two methods AddAttributesToRender and RenderContents), and so on. The following sections analyze the content one by one.
Three attributes of Code Description:
The code above mainly includes three attributes: Email, Text, and TagKey. The Email attribute is used to obtain or set the specific Email address, and the Text attribute is used to obtain or set the Text content displayed by the control. The ViewState of the control view is used in both attribute implementations. The view status of the ASP. NET Server Control is the sum of all its attribute values. ViewState is often used for the implementation of simple attributes. The TagKey attribute is a rewriting attribute inherited from the WebControl base class, which is the key content that readers need to understand. The TagKey attribute is rewritten to present the element in the HTML Tag, so that the default span element of the WebControl class is not displayed. Here, it also implies that the constructor used by the control is protected WebControl () inherited from WebControl. You can return to the previous section to see the description of this constructor. It should be noted that if the element to be presented is a member of the HtmlTextWriterTag enumeration, the TagKey attribute should be rewritten. Many common HTML element tags are mapped to HtmlTextWriterTag enumerated values. For example, System. Web. UI. HtmlTextWriterTag. A corresponds to element a, while System. Web. UI. HtmlTextWriterTag. Table corresponds to the table element. If the element to be rendered is not represented by a member of the HtmlTextWriterTag enumeration, we recommend that you overwrite the TagName attribute and return the string to be rendered as an element.
Two Methods for Code Description:
Two important methods are rewritten in the RenderContentsControl Server Control: AddAttributesToRender and RenderContents.
1) AddAttributesToRender
This method is used to add an Href attribute to the ASP. NET Server Control and set this attribute to "mailto: Email". Email is the attribute that represents the Email address described above. When override the AddAttributesToRender method, always follow the control source code demonstration method: first, call the base class method and then perform relevant settings. In this way, you can add styles and other attributes to the server control. In fact, according to the implementation schematic code of the RenderBeginTag method described above, the AddAttributesToRender method is called by the RenderBeginTag method of WebControl.
2) RenderContents
This method is the core content of this example. It is used to write the hyperlink Text specified by the Text attribute in the mark of the ASP. NET Server Control. As shown in the Code, the server control calls the WriteEncodedText method of the HtmlTextWriter instance to encode the text entered by developers in HTML. Generally, HTML encoding should be performed on the text provided by the user to ensure security.
Metadata attribute tag for Code Description:
Metadata property tags are applied before the class and before the attribute implementation. Descriptions of these metadata property tags have been described in previous articles. Readers can refer to articles on how to create a simple server control. The following describes the internal text persistence issues.
ParseChildren (true, "Text") is set in the metadata attribute mark before the class "). PersistenceMode (PersistenceMode. InnerDefaultProperty) is set in the metadata attribute mark before the Text attribute ). The above two settings Add the internal text persistence settings for the control. This setting allows developers to set the Text attribute in the control tag code. For example:
<Sample: RenderContentsControl runat = "server" ID = "CustomerControl" Email = "my@mysample.com"> my Email address </Sample: RenderContentsControl>
In the code above, the original Text "my mailbox address" should be set by the Text attribute, which is the default persistence). However, due to the internal Text persistence settings, you can set the control text in the control tag.
To implement internal persistence, use ParseChildren (true, "Text") to mark the RenderContentsControl. The first parameter of ParseChildren is true, which is used to specify that the page analyzer should analyze the content in the control label as an attribute rather than a child control. The second parameter provides the default internal property name of the control as Text. When you use these two parameters to call the ParseChildren constructor, the content in the control tag must correspond to the internal default attribute. The PersistenceMode (PersistenceMode. InnerDefaultProperty) of the Text property is used to specify that the visualization designer should serialize this property as the internal content in the control tag.
Generally, the WebControl class uses PersistChildren (false) and ParseChildren (true) to control the persistence of attributes during design and analysis. These two attributes are inherited by the control and must be applied only when you want to change the inherited settings. PersistChildren informs the designer whether to save the child control of the ASP. NET Server Control as a nested internal control. The "false" parameter indicates that the internal content corresponds to the property instead of the Child control. ParseChildren is described in the previous section. If the persistence of the WebControl class applies to your control at design time and analysis time, you do not have to override PersistChildren and ParseChildren inherited from WebControl.
The following lists the source code of the Default. aspx file used to test the server control:
- <%@ Page Language ="C #"AutoEventWireup ="True"
- CodeFile ="Default. aspx. cs"Inherits ="_ Default"%>
- <%@ Register TagPrefix ="Sample"
- Assembly ="UsingRenderContentsControl"Namespace ="UsingRenderContentsControl"%>
- <! 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 id ="Head1"Runat ="Server">
- <Title> display controls using RenderContents </title>
- </Head>
- <Body>
- <Form id ="Form1"Runat ="Server">
- <Div>
- <Sample: RenderContentsControl runat ="Server"
- ID ="CustomerControl"Font-Bold ="True"Font-Size ="Small"
- ForeColor ="Blue"Email =My@mysample.com"> My email address </Sample: RenderContentsControl>
- </Div>
- </Form>
- </Body>
- </Html>
As shown in the Bold code above, the RenderContentsControl control sets Font-Bold, Font-Size, ForeColor, Email, and other attributes, and also sets text content between control tags. Of course, you can also set the Text attribute value to the same Text content. The above code is relatively simple and will not be described here.
In this example, we need to master the RenderContents and AddAttributesToRender methods and the use of TagKey attributes. It is worth noting that although the code of the server control is complicated, the structure is very simple. Do not be overwhelmed by complicated style settings and client behavior code, but be aware of the use process of the two key methods.
After the server control is developed successfully, it is best to view its HTML code and compare the server code with the HTML code to understand each ASP.. NET Server Control Code presents what kind of HTML code. Through this method, I believe that readers can have a deeper understanding of the presentation method of ASP. NET Server controls. The following code is displayed when you run the preceding page in a browser and view the relevant Html source file:
- <! 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 id ="Head1">
- <Title> display controls using RenderContents </title>
- </Head>
- <Body>
- <Form name ="Form1"Method ="Post"Action ="Default. aspx"Id ="Form1">
- <Div>
- <Input type ="Hidden"Name ="_ VIEWSTATE"Id ="_ VIEWSTATE"
- Value ="/WEPDwULLTEyNTQwNjQyMDJkZOlJ3PyMGs2hmzn9MU6Ogt9V + 5ag"/>
- </Div>
- <Div>
- <A id ="CustomerControl"Href ="Mailto: my@mysample.com"
- Style ="Color: Blue; font-size: Small; font-weight: bold ;"> My email address </a>
- </Div>
- </Form>
- </Body>
- </Html>
By observing the above code, we can see that the result of the custom Server Control RenderContentsControl is the code shown in bold, and it is finally displayed as a <a> mark indicating a hyperlink, these include attributes such as href, Style, and text. Their values are closely related to the property settings of the RenderContentsControl control in the source code of the Default. aspx file. For example, the Email attribute value is eventually displayed as the href attribute value. Readers can view the results by themselves, which is helpful for understanding the display of controls.
Summary
This article mainly introduces some basic knowledge of the WebControl class, and uses this basic knowledge to create a simple control rendering instance. In fact, the reader should be able to sum up and create custom server controls inherited from the WebControl base class. The most important method is to rewrite RenderContents. It is very important to remember this. So far, I have used two articles to introduce how to render controls. In future articles, we will introduce the implementation of attributes for ASP. NET Server controls.
The following describes the RenderContents application example of ASP. NET Server controls. I hope you can understand the RenderContents application of ASP. NET Server controls.
- Development of ASP. NET Server controls
- Analysis of ASP. NET Server Control Processing and return data
- Analysis on capture and return events of ASP. NET Server controls
- Analysis of ASP. NET control development-based event processing
- Introduction to RenderContents for ASP. NET Server controls