RenderContents application example of ASP. NET Server Control

Source: Internet
Author: User
Tags control label

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.

 
 
  1. UsingSystem;
  2. UsingSystem. ComponentModel;
  3. UsingSystem. Security;
  4. UsingSystem. Security. Permissions;
  5. UsingSystem. Web;UsingSystem. Web. UI;
  6. UsingSystem. Web. UI. WebControls;
  7. NamespaceUsingRenderContentsControl {
  8. [
  9. AspNetHostingPermission (SecurityAction. Demand,
  10. Level = AspNetHostingPermissionLevel. Minimal ),
  11. AspNetHostingPermission (SecurityAction. InheritanceDemand,
  12. Level = AspNetHostingPermissionLevel. Minimal ),
  13. DefaultProperty ("Email"), ParseChildren (True,"Text"),
  14. ToolboxData ("<{0}: RenderContentsControl runat = server ></{ 0}: RenderContentsControl>")
  15. ]
  16.  
  17.  Public ClassRenderContentsControl: WebControl {
  18. // Implement Email attributes 
  19. [Bindable (True)]
  20. [Category ("Appearance")]
  21. [DefaultValue ("")] [Localizable (True)]
  22.  
  23. Public StringEmail
  24. {
  25.  Get{
  26. String s = (String) ViewState ["Email"];
  27. Return(S =Null)? String. Empty: s );
  28. }
  29.  Set{
  30. ViewState ["Email"] = Value;
  31. }
  32. }
  33. // Implement the Text attribute 
  34.  
  35. [
  36. Bindable (True), Category ("Appearance"), DefaultValue (""), Localizable (True),
  37. PersistenceMode (PersistenceMode. InnerDefaultProperty)
  38. ]
  39.  
  40. Public Virtual StringText
  41. {
  42.  Get{
  43. StringS = (String) ViewState ["Text"];
  44. Return(S =Null)? String. Empty: s;
  45. }
  46.  Set{
  47. ViewState ["Text"] = Value;
  48. }
  49. }
  50. // Rewrite the TagKey attribute 
  51.  
  52. Protected OverrideHtmlTextWriterTag TagKey
  53. {
  54.  Get{
  55. ReturnHtmlTextWriterTag.;
  56. }
  57. }
  58.  
  59. // Override the AddAttributesToRender Method 
  60.  
  61. Protected Override VoidAddAttributesToRender (HtmlTextWriter writer)
  62. {
  63.  Base. AddAttributesToRender (writer );
  64. Writer. AddAttribute (HtmlTextWriterAttribute. Href,"Mailto :"+ Email );
  65. }
  66.  
  67. // Rewrite the RenderContents Method 
  68.  
  69. Protected Override VoidRenderContents (HtmlTextWriter writer)
  70. {
  71.  If(Text = String. Empty ){
  72. Text = Email;
  73. }
  74. Writer. WriteEncodedText (Text );
  75. }
  76. }
  77. }

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:

 
 
  1. <%@ Page Language ="C #"AutoEventWireup ="True" 
  2. CodeFile ="Default. aspx. cs"Inherits ="_ Default"%>
  3. <%@ Register TagPrefix ="Sample"
  4. Assembly ="UsingRenderContentsControl"Namespace ="UsingRenderContentsControl"%>
  5. <! DOCTYPE html PUBLIC"-// W3C // dtd xhtml 1.0 Transitional // EN" 
  6. Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  7. <Html xmlns =Http://www.w3.org/1999/xhtml">
  8. <Head id ="Head1"Runat ="Server">
  9. <Title> display controls using RenderContents </title>
  10. </Head>
  11. <Body>
  12. <Form id ="Form1"Runat ="Server">
  13. <Div>
  14. <Sample: RenderContentsControl runat ="Server"
  15. ID ="CustomerControl"Font-Bold ="True"Font-Size ="Small" 
  16. ForeColor ="Blue"Email =My@mysample.com"> My email address </Sample: RenderContentsControl>
  17. </Div>
  18. </Form>
  19. </Body>
  20. </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:

 
 
  1. <! DOCTYPE html PUBLIC"-// W3C // dtd xhtml 1.0 Transitional // EN" 
  2.  Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <Html xmlns =Http://www.w3.org/1999/xhtml">
  4. <Head id ="Head1">
  5. <Title> display controls using RenderContents </title>
  6. </Head>
  7. <Body>
  8. <Form name ="Form1"Method ="Post"Action ="Default. aspx"Id ="Form1">
  9. <Div>
  10. <Input type ="Hidden"Name ="_ VIEWSTATE"Id ="_ VIEWSTATE"
  11. Value ="/WEPDwULLTEyNTQwNjQyMDJkZOlJ3PyMGs2hmzn9MU6Ogt9V + 5ag"/>
  12. </Div>
  13. <Div>
  14. <A id ="CustomerControl"Href ="Mailto: my@mysample.com"
  15. Style ="Color: Blue; font-size: Small; font-weight: bold ;"> My email address </a>
  16. </Div>
  17. </Form>
  18. </Body>
  19. </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.

  1. Development of ASP. NET Server controls
  2. Analysis of ASP. NET Server Control Processing and return data
  3. Analysis on capture and return events of ASP. NET Server controls
  4. Analysis of ASP. NET control development-based event processing
  5. Introduction to RenderContents for ASP. NET Server controls

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.