ASP. NET2.0 Server Control Render Method

Source: Internet
Author: User

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. The text will be converted to visualized elements through the client browser. By using controls, developers can enter HTML tags, script code, CSS style sheets, and so on into the client browser. There are two main ways to Render server controls: one is the Control Render method and the other is the WebControl RenderContents method. This article describes how to use the Control Render method to display controls.

  Use the HtmlTextWriter class

The Render method of the Control class is mainly used to implement Control rendering. The declared code is as follows:

Protected virtual void Render (HtmlTextWriter output)


As shown in the above Code, the parameter of the Render method is of the HtmlTextWriter type. To better apply the Render method, you should first understand the HtmlTextWriter class and its related content.

According to the description in MSDN2005, The HtmlTextWriter class is used to write the markup characters and text into the output stream of the ASP. NET Server Control. This class provides the format setting function used by ASP. NET Server controls to present tags to clients. To implement the class function, the HtmlTextWriter class defines multiple fields, attributes, and methods. Due to the large number of member objects, this article only selects some common members to describe, and also introduces some newly added members of ASP. NET 2.0.

Common Member objects include:

· AddAttribute Method

For the HtmlTextWriter object, add the specified tag attribute and value to the start tag of the element created by subsequent calls to the renderbegbegintag method.

· AddStyleAttribute Method

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

· Write Method

Write the specified data type together with any pending tab spacing to the output stream.

· WriteAttribute Method

Write tag attributes and their values to the output stream.

· WriteBeginTag Method

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

· WriteEndTag Method

Write any tab spacing and end tag of the specified tag element.

· Encoding attributes

Obtains the encoding of the HtmlTextWriter object used to write content into the page.

· Indent attributes

Gets or sets the number of tabs used to indent the start position of each line.

· NewLine attributes

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

For beginners, it is recommended that you master the application of the above Member objects. In addition, ASP. NET 2.0 adds some members to the HtmlTextWriter class, including:

· BeginRender Method

Notifies the HtmlTextWriter object or the object of the derived class. A control is displayed.

· EndRender Method

Notifies the HtmlTextWriter object or the object of a derived class that a control has been rendered.

· IsValidFormAttribute Method

Check an attribute to make sure it can be rendered in the start tag of the <form> tag element.

· WriteEncodedUrl Method

Encode the specified URL and write it to the output stream. The URL can contain parameters.

· WriteEncodedText Method

Encode the specified text of the requested device and write it to the output stream.

· WriteBreak Method

Write the <br/> flag element to the output stream.

  Render controls using the Render Method

1. Basic Knowledge

The Render method described in this article belongs to the System. Web. UI. Controls. Control class. This class is the base class for creating server controls. Many control classes inherit from this class. The Control class contains three methods for rendering controls: Render, RenderChildren, and RenderControl. Both use HtmlTextWriter instances as parameters. They allow the server control content to be provided for an HtmlTextWriter object and encapsulate its content into an HTTP output stream and output it to the client for display. The following is a brief introduction to these three methods.

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

This method is used to send the server control content to the provided HtmlTextWriter object, which is written into the content that will be presented on the client. When developing 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 child-level content of the server control to the provided HtmlTextWriter object, which is written in the client. This method notifies ASP. NET of All Active Server Pages On the rendering page. If there is no ASP code on the page, this method will render all the child controls of the server control.

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

RenderControl has two overload methods, which are used to output the content of the server control to the provided HtmlTextWriter object. If the tracking function is enabled, trace information about controls is stored. If the Visible attribute of the server control is set to true, this method determines whether the page tracking function is enabled. If enabled, it stores control-related trace information and presents the content of the server control to the page. In addition, the previous overload method is inherited by ASP. NET 2.0 from ASP. NET 1.0, and the last overload method is added by ASP. NET 2.0. The latter uses the provided ControlAdapter object to output the server control content to the provided HtmlTextWriter object. The adapter parameter is of the ControlAdapter type and is used to define the rendered ControlAdapter. This method is commonly used to implement server controls running on various devices and browsers.

The above three methods seem to be independent of the three methods. However, there is actually a close relationship between them. Readers can understand the relationship between them by reading the following schematic code.

// Basic implementation of the RenderCotrol Method
Public void RenderControl (HtmlTextWriter output)
{
If (Visible)
{
Render (output );
}
}
// Basic implementation of the Render Method
Protected virtual void Render (HtmlTextWriter output)
{
RenderChildren (output );
}
// Basic implementation of the RenderChildren Method
Protected virtual void RenderChildren (HtmlTextWriter output)
{
Foreach (Control c in Controls)
{
C. RenderControl (output );
}
}
The code above lists the Implementation ideas of the RenderControl, Render, and RenderChildren methods. Obviously, these three methods play a role in the control rendering process, and a simple recursive call process is used. In general, it can be understood:

(1) Create an HtmlTextWriter class instance in the page framework;

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

(3) The RenderControl method checks whether the Visible property Visible of the control is true. If the value is true, the RenderControl method calls the Render method. If the value is false, the Control and Its subcontrols are not displayed;

(4) The Render method is implemented by default and the RenderChildren method is called;

(5) The RenderChildren method calls the RenderControl method of each sub-control according to the settings in the default implementation;

In fact, it does not matter if you cannot understand the above process in a short time. For beginners, the key is to remember the most important and commonly used Render method. The control developer can override the Render method to complete the rendering control task.

2. Example Application

The previous section describes the basic knowledge of using the Control Render method to Render controls. The following is a typical example to help you understand how to use Render. Example 1 is shown.


Figure 1
As shown in 1, the server control presents a hyperlink and sets the text to red. When a user clicks the red text, the page is directed to the Microsoft Site. Of course, you can set the hyperlink address through the link URL attribute.

The following is an example of source code implementation.

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 ;}
}
// Rewrite the Render Method
Protected override void Render (HtmlTextWriter writer)
{
Writer. AddAttribute (HtmlTextWriterAttribute. Href, LinkUrl );
Writer. AddStyleAttribute (HtmlTextWriterStyle. Color, "red ");
Writer. RenderBeginTag (HtmlTextWriterTag. );
Writer. Write ("Browse website ");
Writer. RenderEndTag ();
}
}
}
The code above implements the RenderControl class for custom server controls. This class inherits from the Control base class, implements the LinkUrl (default value: http: // localhost/) that represents the hyperlink address, and overwrites the Render method. During Render rewriting, some HtmlTextWriter class members are called, such as Writer, addattriattribute, AddStyleAttribute, RenderBeginTag, and RenderEndTag. In addition, developers may need to present a long string when using the Writer method. We recommend that you use the Writer method instead of the string cascade or StringBuilder method. Because it will consume a lot of system time and memory, and the efficiency is low.

Some readers may ask, if the order of the multi-line code displayed by the server control changes, what is the difference? For example, if you first apply the RenderBeginTag, Write, and RenderEndTag methods in sequence, and then call the AddAttribute and AddStyleAttribute methods, will the same effect be displayed? The answer is no. It should be emphasized that, in the process of rendering the control, you must first define the attributes and CSS styles of the server control, and then define the main content of the server control, this order cannot be changed.

In addition, if you are interested, you can implement a Text attribute in the code to obtain or set the Text displayed by the control. In this way, the "Browse Website" Text output by using the Write method can be replaced by the Text attribute in the Render method.

The source code of the Default. aspx file created to use the above custom Server Control is listed below.

<% @ 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">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> display controls using the Render method </title>
</Head>
<Body>
<Form id = "form1" runat = "server">
<Div>
<Sample: RenderControl runat = "server" ID = "CustomerControl" LinkUrl = "http://www.microsoft.com/">
</Sample: RenderControl>
</Div>
</Form>
</Body>
</Html>
The above code is relatively simple, which mainly declares the custom Server Control RenderControl, and set its LinkUrl property value to http://www.microsoft.com, that is, the Microsoft site address.

When you run the preceding page in a browser and view the relevant Html source files, you can get the following code:

<! 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>
<Title> display controls using the Render method </title>
</Head>
<Body>
<Form name = "form1" method = "post" action = "Default. aspx" id = "form1">
<Div>
<Input type = "hidden" name = "_ VIEWSTATE" id = "_ VIEWSTATE" value = "/wEPDwUJNzMyMTY5NTU2ZGQQYrLd/G + vm1h41r2CEkxID63o5g ="/>
</Div>
<Div>
<A href = "http://www.microsoft.com/" style = "color: red;"> browse websites </a>
</Div>
</Form>
</Body>
</Html>
By observing the above code, we can see that the result of the custom Server Control RenderControl is the code shown in bold, which is finally displayed as a <a> flag indicating a hyperlink.

   Summary

This article first introduces the basic knowledge of the HtmlTextWriter class, and then explains the application of using the Render method to implement control rendering. In a subsequent article, I will explain another method to implement control rendering. In general, the control rendering technology is the most common and simple content in the development process. It is recommended that you be familiar with 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.