asp.net2.0 server Control Render method _ Practical Tips

Source: Internet
Author: User
Tags html tags
Control rendering is the process of writing markup text to the HTTP output stream. The server sends the generated markup text to the client through the HTTP output, which is displayed through the conversion of the client browser to a visual element. With control rendering, developers can enter HTML tags, script code, CSS stylesheet, and so on to the client browser. There are two main ways to implement the server control rendering: One is the Render method and the other is the WebControl rendercontents method. This article focuses on the use of the control class render method to implement the application of controls rendering.

   using the HtmlTextWriter class

The Render method of the control class is primarily used to implement the rendering of controls, whose declaration code is as follows:

protected virtual void Render (HtmlTextWriter output)


As shown in the code above, the parameter of the Render method is a HtmlTextWriter type. In order to better apply the Render method, the reader should first understand the HtmlTextWriter class and its related content.

According to the MSDN2005 description, the HtmlTextWriter class is used to write markup characters and text to the ASP.net server control output stream. This class provides the formatting features that ASP.net server controls use when rendering markup to clients. To implement the functionality of a class, the HtmlTextWriter class defines multiple fields, properties, and methods. Due to the large number of member objects, this article only selected some of the common members to explain, and will also introduce some ASP.net 2.0 new members.

Common member objects include:

· AddAttribute method

For the HtmlTextWriter object, add the specified tag properties and values to its opening tag by the element created by subsequent calls to the RenderBeginTag method.

· AddStyleAttribute method

For the HtmlTextWriter object, add the tag style attribute to its opening tag by the element created by subsequent calls to the RenderBeginTag method.

· Write method

Writes the specified data type along with any pending tab spacing to the output stream.

· WriteAttribute method

Writes a tag property and its value to the output stream.

· WriteBeginTag method

Any tab spacing and the start tag of the specified markup element are written to the output stream.

· Writeendtag method

Writes any tab spacing and closing tags for the specified markup element.

· Encoding Property

Gets the encoding that the HtmlTextWriter object uses to write content to the page.

· Indent Property

Gets or sets the number of tab positions that are used to indent the start position of each line of markup.

· NewLine Property

Gets or sets the line terminator string used by the HtmlTextWriter object.

For beginners, we should focus on the application of the above member objects. In addition, ASP.net 2.0 has added a number of members to the HtmlTextWriter class, including:

· Beginrender method

Notifies the object of the HtmlTextWriter object or derived class that a control will be rendered.

· Endrender method

Notifies the HtmlTextWriter object or an object of a derived class that a control has finished rendering.

· Isvalidformattribute method

Check a property to make sure that it can be rendered in the opening tag of the <form> markup element.

· WriteEncodedUrl method

Encodes the specified URL and writes it to the output stream. URLs can include parameters.

· Writeencodedtext method

Encodes the specified text of the requested device and writes it to the output stream.

· Writebreak method

Writes the <BR/> markup element to the output stream.

   implementing control rendering using the Render method

1. Basic knowledge

The Render method explained in this article belongs to the System.Web.UI.Controls.Control class. The class is the base class for creating server controls, and many control classes inherit from that class. The control class includes three methods for implementing the rendering of controls: Render, RenderChildren, and RenderControl. They all use instances of HtmlTextWriter as arguments that allow the contents of the server control to be supplied for a HtmlTextWriter object and encapsulate its contents into the HTTP output stream for output to the client display. The following is a simple introduction to these three methods.

(1) protected virtual void Render (HtmlTextWriter writer);

This method is used to send server control content to the provided HtmlTextWriter object, which writes the content that will be rendered on the client. When you develop a server control, you can override this method to render the server control.

(2) protected virtual void RenderChildren (HtmlTextWriter writer);

This method is used to output the contents of the server control's child to the provided HtmlTextWriter object, which writes the content that will be rendered on the client. This method notifies asp.net to render all active Server pages code in the page. If there is no ASP code on the page, this method renders all child controls of the server control.

(3) protected virtual void RenderControl (HtmlTextWriter writer) and protected void RenderControl (HtmlTextWriter writer, ControlAdapter adapter)

RenderControl has two overloaded methods that are used to output the contents of a server control to the provided HtmlTextWriter object. If tracing is enabled, trace information about the control is stored. If the Visible property of the server control is set to True, the method determines whether the page's tracing function is enabled. If enabled, it stores trace information about the control and renders the contents of the server control to the page. In addition, the previous overload method is ASP.net 2.0 from ASP.net 1.0, and the latter overload is ASP.net 2.0 added. The latter specifically uses the provided ControlAdapter object to output server control content to the provided HtmlTextWriter object. Where the parameter adapter is a ControlAdapter type, it is used to define the rendered controladapter. This method is more commonly used when implementing server controls that run in various devices and browsers.

The above 3 methods look as if they are independent of 3 methods, however, in fact there is a close relationship between them. Readers can understand the relationship between them by reading the following schematic code.

Basic realization of Rendercotrol method
public void RenderControl (HtmlTextWriter output)
{
if (Visible)
{
Render (output);
}
}
Basic realization of Render method
protected virtual void Render (HtmlTextWriter output)
{
RenderChildren (output);
}
Basic realization of RenderChildren method
protected virtual void RenderChildren (HtmlTextWriter output)
{
foreach (Control C in Controls)
{
C.rendercontrol (output);
}
}

As shown in the code above, it lists the RenderControl, Render, RenderChildren methods of implementation. Obviously, these three methods work in the control rendering process, and a simple recursive call procedure is used. Broadly speaking, it can be understood that:

(1) The page framework establishes an example of a HtmlTextWriter class;

(2) The page frame passes this instance object to the RenderControl method;

(3) The RenderControl method checks whether the control's visual property visible is true. If the Render method is invoked for the True,rendercontrol method, or false, the control and its child controls are not rendered;

(4) The Render method executes the default implementation and invokes the RenderChildren method;

(5) The RenderChildren method calls the RenderControl method of each child control according to the setting in the default implementation;

In fact, if the reader can not understand the above process in a short period of time is not a big relationship. For beginners, the key is to remember that the most important and most commonly used is the Render method. The control developer can complete the task of rendering the control by overriding the Render method.

2. Sample Application

The basics of using the Render method of the control class to implement the rendering of controls are described above. The following is a typical example to help readers understand how render is used. The example effect is shown in Figure 1.


Figure 1 Effect chart

As shown in Figure 1, the server control renders a hyperlink, and the text is set to red. When the user clicks the red text, the page is turned to the Microsoft site. Of course, the user can set the hyperlink address through the attribute Linkurl.

The example implementation source code is listed below.

Using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Text;
Using System.Web;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Namespace Usingrendercontrol
{
[Defaultproperty ("Linkurl")]
[ToolBoxData ("<{0}:rendercontrol runat=server> </{0}:RenderControl>")]
public class Rendercontrol:control
{
Implement Linkurl
[Bindable (True)]
[Category ("appearance")]
[DefaultValue ("http://localhost/")]
[Localizable (true)]
public string Linkurl
{
get {string s = (string) viewstate["Linkurl"];
Return ((s = = null)? STRING.EMPTY:S);}
set {viewstate["linkurl"] = value;}
}
Overriding the Render method
protected override void Render (HtmlTextWriter writer)
{
Writer. AddAttribute (Htmltextwriterattribute.href, Linkurl);
Writer. AddStyleAttribute (Htmltextwriterstyle.color, "Red");
Writer. RenderBeginTag (HTMLTEXTWRITERTAG.A);
Writer. Write ("Browsing the web");
Writer. RenderEndTag ();
}
}
}

The code above implements the custom server control class RenderControl. The class inherits from the control base class, implements the Linkurl that represents the hyperlink address (the default is http://localhost/), and overrides the Render method. During the rewriting of render, some HtmlTextWriter class members were invoked, such as Writer, AddAttribute, AddStyleAttribute, RenderBeginTag, and RenderEndTag methods. In addition, it is possible for a developer to render a longer string in the process of using the writer method. It is recommended that you use the writer method a lot at this time instead of using string-cascading or StringBuilder-class related methods. Because that would consume a lot of system time and memory and be less efficient.

Some readers may ask if the sequence of multiple lines of code rendered by a server control changes, what would be the difference? For example, suppose you first apply the RenderBeginTag, Write, RenderEndTag methods, and then call the AddAttribute and AddStyleAttribute methods, and then the same effect is displayed? The answer is in the negative. Here's what you need to emphasize: in the process of rendering a control, you first define the properties of the server control and CSS styles, and so on, and then define the main contents of the server control, which cannot be changed.

In addition, if the reader is interested, you can implement a text property in your code to get or set the text that the control displays. Thus, in the Render method, the text content of the browse Web site output using the Write method can be replaced by the Text property.

The following is an enumeration of the Default.aspx file source code created to use the above custom server controls.

<%@ Page language= "C #" autoeventwireup= "true" codefile= "Default.aspx.cs" inherits= "_default"%>
<%@ Register tagprefix= "Sample" assembly= "Usingrendercontrol" namespace= "Usingrendercontrol"%>
! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<title> implement control rendering using the Render method </title>
<body>
<form id= "Form1" runat= "Server"
<div>
<sample:rendercontrol runat= "Server" id= "Customercontrol" linkurl= "http://www.microsoft.com/"
</Sample:RenderControl>
</div>
</form>
</body>
The above code is relatively simple, which mainly declares the custom server control RenderControl and sets its Linkurl property value to http://www.microsoft.com, that is, the Microsoft site address.

When the user runs the page above in the browser and looks at the related HTML source file, you get the following code:

! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

implement control rendering using the Render method









By looking at the above code, you can see that the custom server control RenderControl actually renders the code in bold, which is ultimately rendered as a <a> tag that represents a hyperlink.

   Summary

  This paper first introduces the basic knowledge of HtmlTextWriter class, and then explains the application of using Render method to implement control rendering. In a subsequent article, I will explain another way to implement control rendering. From the server control development technology overall, the control rendering technology is the most common and simplest content in the development process. The reader is advised to be proficient in the content.
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.