Customizing server controls (Getting started)

Source: Internet
Author: User
Tags control label opening and closing tags

Transferred from: http://www.cnblogs.com/SkySoot/archive/2012/11/22/2782916.html

Each custom control has its advantages and disadvantages. A user control was previously introduced. user controls are easier to create than custom server controls, but server controls are more powerful.

server controls are much stronger in two ways than user controls:

    • server controls allow full control of the generated HTML
    • server controls provide better design-time support

All of the ASP. NET WEB controls are server controls. Now you will learn how to create your own server controls.

Getting started with custom server controls

server controls refer to. NET classes that derive directly or indirectly from the System.Web.UI.Control class. The control class provides properties and methods that are common to all server controls (such as id,viewstate and controls collections, and so on).

Many controls cannot derive directly from the control class, they are derived from the System.Web.UI.WebControls.WebControl class. This class adds features to help you implement standard styles, including properties such as Font, ForeColor, BackColor, and so on.

To better understand how custom controls work, here are a few examples of simple custom controls.

Create a simple custom control

In order to create a basic custom control, your class needs to derive from the control class and overwrite the Render () method. Render () receives an HtmlTextWriter object that is used to generate HTML for the control.

The simplest way to generate HTML code is to use the HtmlTextWriter.Write () method to write an original HTML string to the page. Obviously, you cannot use the Write () method to output an ASP. NET tag or other server-side content because it renders the content for the final page before it is sent to the client.

public class Linkcontrol:control
{
    Inherit the Control class, overriding the Render method to output a label
    protected override void Render (HtmlTextWriter writer)
    {
        Writer. Write ("<a href= ' http://www.apress.com ' >click to visit apress</a>");
    }
}

The HtmlTextWriter class not only allows you to write the original HTML, but also provides some helpful ways to help you manage style features and tags. The next example gives the same control, but slightly different. First it uses RenderBeginTag () and RenderEndTag () to separate the opening and closing tags of the anchor tag, and secondly, it adds the style attributes that configure how the control is displayed:

public class Linkcontrol:control
{
    protected override void Render (HtmlTextWriter writer)
    {
        Writer. AddAttribute (Htmltextwriterattribute.href, "http://www.apress.com");
        Writer. AddStyleAttribute (Htmltextwriterstyle.fontsize, "20");
        Writer. AddStyleAttribute (Htmltextwriterstyle.color, "Blue");
        Writer. RenderBeginTag (HTMLTEXTWRITERTAG.A);
        Writer. Write ("Click to visit Apress");
        Writer. RenderEndTag ();
    }
}

You should be aware of some of the points in this example. First, in order to simplify, the example uses several enumerations that help avoid unexpected problems caused by minor typographical errors.

    • HtmlTextWriterTag : This enumeration defines a number of HTML tags, such as <a>, <p>, <font>, and so on.
    • HtmlTextWriterAttribute : This enumeration defines a number of common HTML tag features, such as OnClick, href, align, alt, and so on.
    • HtmlTextWriterStyle : This enumeration defines 14 style attributes, including BackgroundColor, BackgroundImage, BorderColor, BorderStyle, BorderWidth, Color, FontFamily, FontSize, FontStyle, FontWeight, Height, Width. All of this fragmented information is concatenated in a semicolon-delimited form, creating a list of CSS style information that is used to present the style characteristics of the label.

when Render () executes, it first defines all the attributes that will be added to subsequent labels, and then creates the start tag, all of which are placed inside the tag . The final label appears as follows:

<a href= "http://www.apress.com" style= "Font-size:20;color:blue;" >click to visit apress</a>

Key methods of HtmlTextWriter class

AddAttribute () Add any HTML attribute and its value to a HtmlTextWriter output stream. This feature is automatically applied to the next label created by calling RenderBeginTag (). (with enumeration values optional)
AddStyleAttribute Add any HTML style attributes and their values to a HtmlTextWriter output stream. This feature is automatically applied to the next label created by calling RenderBeginTag (). (with enumeration values optional)
RenderBeginTag () The start tag for the output HTML element. (with enumeration values optional)
RenderEndTag () Outputs the end tag of the current HTML element without specifying a label name
WriteBeginTag () Similar to RenderBeginTag (), but does not output the end character of the start tag >. This means that you can call WriteAttribute () to add more attributes to the label. To close the start tag, you can call Write (Htmltextwriter.tagrightchar)
WriteAttribute () Outputs an attribute to the output stream, which must be followed by the WriteBeginTag () call
Writeendtag () Outputs an end symbol for an element to the current HTML element

Using the custom control

To use the custom control, you need to make it available in the Web application. There are two ways of doing this:

    • Copy the source code into the App_Code directory
    • Add the compiled assembly to the Bin directory (add Reference)

for those pages that can use custom controls, you must use the Register directive (similar to the user control) to include not only a TagPrefix tag, but also the assembly file , and The namespace in which the control class resides . You do not need to specify TagNamebecause the class name of the server control is automatically used.

<%@ Register TagPrefix= "Apress" Assembly= "Userdesigncontrol" Namespace= " Userdesigncontrol "%>

If the control is in the App_Code directory of the current WEB program, the Assembly attribute is not required.

<%@ Register TagPrefix= "Apress" Namespace= "Userdesigncontrol"%>

You can reuse tag prefixes, in other words, mapping two different namespaces or two completely different assemblies to the same tag prefix is completely valid.

If you want to use the same control on multiple pages in the same WEB application, you can configure the Web. config file in the following ways:

<configuration>
  <system.web>
    <pages>
      <controls>
        <add tagprefix= "Apress" namespace= "Userdesigncontrol" assembly= "Userdesigncontrol"/>
      </controls>
    </pages>
    ...
  </system.web>
</configuration>

When you drag a control from the VS Toolbox, vs chooses a default prefix. However, once you have configured Web. config, you can standardize your control prefixes.

Custom controls in the Toolbox

For ease of use, you might want to have these custom controls appear in the toolbox. If you create a custom control in a separate assembly, the VS Toolbox has built-in support for custom controls.

Once you have created the project, you can define the control. Control library projects are developed in the same way that other DLL components are developed. You can build the project at any time, but you cannot start it directly because it is not an actual application. In order to test the controls, you need to use them in another application.

VS Each time the project is compiled, the latest version of the referenced assembly is copied to the Bin directory of the Web application, that is, without worrying about updating the referenced control version.

The Automatic toolbox (when you design the tab ) automatically detects the custom controls contained in the WEB program and adds it to a temporary project-specific zone:

If you want the control to be available in any Web program, but you do not want the Web application developer to change the code for your custom control, in which case you only need to deploy the compiled assembly. You can then permanently add these controls to the Toolbox (tab lookup Assemblies).

To create a Web control that supports style properties

The previous custom example does not allow a Web page to customize the appearance of the control. The Linkcontrol control does not provide any properties to set the foreground color, background color, font, and other attributes of the generated HTML tags. In other words, the Linkcontrol control does not allow external code to alter the HTML it generates. To be more flexible, you need to explicitly add public properties that represent these property values, and then you need to read the properties in Render () and generate the appropriate HTML code.

Style attributes are a fundamental part of the infrastructure used by many HTML controls. Ideally, all controls should follow a simplified model of the same valid style information, and do not force the developer of the custom control to write this common function themselves. ASP. NET implements this through the WebControl base class (System. Web.UI.Controls in the namespace). each control in ASP. NET derives from the WebControl class, so you can also derive a custom control from the WebControl class.

The WebControl class contains not only basic style-related properties, such as Font, ForeColor, BackColor, etc., but it also automatically renders these attributes in the control label . Here's how it works: WebControl assumes that it should add these attributes to an HTML tag called the base tag (base tag), and if you are outputting multiple elements, these attributes are added to the outermost element that contains the other elements. You should specify a basic label for the Web control in the constructor.

Ultimately, you don't have to overwrite the render () method, the WebControl class already contains the implementation of render (), which is made up of the following 3 methods:

    • RenderBeginTag(): The start tag of the output control and the attributes you specify
    • rendercontents(): outputs all content in the middle of the start and end tags, including text content and other HTML tags. This method is often overridden to export the contents of a custom control
    • RenderEndTag(): End label for output control

Of course, you can change this behavior by overriding the Render () method if necessary. However, if this basic framework is appropriate for your needs, you can simply write a few custom code to achieve the desired functionality .

The next example shows a new link control derived from WebControl, resulting in automatic support for style attributes:

public class Linkwebcontrol:webcontrol
{
    WebControl has multiple versions of constructors, which have constructors that allow you to pass in tags
    The basic control label passed here is the anchor tag <a>
    Public Linkwebcontrol ()
        : Base (HTMLTEXTWRITERTAG.A)
    {
        The constructor does not require any code.
        The only important thing is to use this opportunity to invoke the WebControl constructor to set the basic control label
    }
    Define two properties to allow Web pages to set text and URLs
    public string Text {get; set;}
    private string HyperLink;
    public string HyperLink
    {
        get {return hyperLink;}
        Set
        {
            if (value. IndexOf ("http://") = =-1)
            {
                throw new ApplicationException ("Specify HTTP as the Protocol");
            }
            Else
            {
                HyperLink = value;
            }
        }
    }
    When defining text and hyperlink variables, you can set it to an empty string
    The OnInit () method is intentionally overridden here to show how to initialize a control programmatically
    protected override void OnInit (EventArgs e)
    {
        Base. OnInit (e);
        If no value were set in the control tag, apply the defaults now.
        if (HyperLink = = null)
            HyperLink = "http://www.google.com";
        if (Text = = null)
            Text = "click to search";
    }
    The WebControl class can override the following methods so that additional tags can be added
    protected override void AddAttributesToRender (HtmlTextWriter writer)
    {
        Writer. AddAttribute (Htmltextwriterattribute.href, this. HyperLink);
        Base. AddAttributesToRender (writer);
    }
    Add text
    protected override void RenderContents (HtmlTextWriter writer)
    {
        Writer. Write (this. Text);
        Base. RenderContents (writer);
    }
}

Note that whenever a custom control overrides a method, it should call the implementation of the base class through base. Doing so ensures that you don't accidentally suppress other code that needs to run . Typically, the base class method is to fire a related event. For example, if you overwrite the RenderBeginTag () method and do not call the base class implementation, the rendering code will fail and throw an unhandled exception because the label is not open.

Custom server controls in Visual Studio

There is an important difference between manually created controls and Visual Studio-generated controls. The controls generated by VS contain some auto-generated boilerplate code:

    • The beginning of a file has a set of using statements that import useful ASP. NET namespaces
    • The control class adds the Text property, which is saved in view state
    • The control class overrides RenderContents () to output the contents of the Text property
    • The control class declaration and the Text property are configured with design-time-supported attribute adornments (such as Defaultproperty for highlighted properties when the control is selected)

Without the help of VS, adding these details is also very easy. So you don't have to be afraid of empty code files and manually writing custom control classes.

Rendering process

The previous example shows several new rendering methods, and now let's see how they work together.

The starting point of the rendering process is the RenderControl () method. RenderControl () is a public rendering method that ASP. NET renders each control as HTML, and you cannot overwrite it. RenderControl () invokes the render () method that initiates the rendering process, and you can override this method, as shown in the first example. However, if you override the render () method without invoking the base class implementation of the render () method, the other rendering methods are not fired.

The base class implementation of the Render () method calls the RenderBeginTag (), RenderContents (), RenderEndTag () methods, as shown in the preceding example. There is also an episode where the base class implementation of the RenderContents () method invokes another rendering method, RenderChildren (). This method iterates through the collection of child controls in the Controls collection and invokes the RenderControl () method of each child control. In this way, you can easily build your own controls based on other controls. I'll introduce you in the subsequent combinations of control articles.

So, which rendering method should be covered?

    • You can override the render () method if you want to replace the entire rendering process with new content, or if you want to add HTML content (such as Javascript code blocks) before the base control label.
    • If you want to take advantage of the automatic styling features, you should define a basic tag (call the base class constructor and specify the tag name parameter) and overwrite RenderContents ().
    • If you want to prevent child controls from being displayed or to customize how they are rendered (for example, to render them in reverse order), you can overwrite RenderChildren ().

It is important to note that you can call the RenderControl () method to check the HTML output of a control, which is a convenient way to debug:

StringWriter writer = new StringWriter ();
HtmlTextWriter output = new HtmlTextWriter (writer);
Linkwebcontrol1.rendercontrol (output);
label1.innerhtml = "The HTML for LinkWebControl1 is <br/><blockquote>"
    + Server.HTMLEncode (writer. ToString ()) + "<blockquote/>";

This method is not just for debugging, it can also be used to simplify your rendering code. For example, you might find it easier to create and configure a HtmlTable control and then call its RenderControl () method instead of directly outputting <table>, <tr>, <td> tags to the output stream.

Customizing server controls (Getting started)

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.