Asp. NET server control development (1) Encapsulation Html_ practical Tips

Source: Internet
Author: User
Tags data structures form post garbage collection html tags shallow copy

In our project development, because of the limited functionality of ASP.net server controls, we often define our own specific server controls to meet the specific business requirements of development. It is important to know how to develop ASP.net server controls.

In fact, the simple implementation of ASP.net server control is not difficult, before the garden has introduced the corresponding content Daniel, here standing on the shoulders of Giants also to share under the development of ASP.net server control methods and some of their own experience. Write to the Novice, the master bypasses.

Learning ASP.net server control development, the individual thinks the best way is to practice their own, of course, theoretical knowledge is also very important, but if we just look at the theory of knowledge, may be inside some of the concept of confusion, looking at the fall asleep, if they do create a control of their own, the effect is not the same.

The following example creates a simple server control:

First we create a class library engineering Selfwebcontrol. In the same solution we are creating a asp,net Web application (to test our controls)

Namespace Selfwebcontrol
{public
  class Controla:control//control class defines properties and methods
  {} for all ASP.net server control shares
}

I will inherit the control class from the ControlA class, which is the base class for all the controls in. NET, and contains the properties and methods common to the control.

Control class

Public properties:

ClientID gets the server control identifier generated by asp.net.

Controls gets the ControlCollection object that represents the child controls of the specified server control in the UI hierarchy.

EnableViewState Gets or sets a value that indicates whether the server control maintains its own view state and the view state of any child controls it contains to the requesting client.

ID Gets or sets the programmatic identifier assigned to the server control.

NamingContainer gets a reference to the server control's naming container, which creates a unique namespace to differentiate between server controls that have the same Control.id property values.

Page gets a reference to the page instance that contains the server control.

Parent gets a reference to the parent control of the server control in the page UI hierarchy.

Site gets information about the WEB site that the server control belongs to (from MSDN, but I do not think it should be the container site for the component, not the Web site).

TemplateSourceDirectory gets the virtual directory that contains the page or UserControl of the current server control.

UniqueID gets the unique, hierarchically qualified identifier of the server control.

Visible Gets or sets a value that indicates whether the server control is rendered as a UI on the page.

Public methods:

DataBind binds the data source to the invoked server control and all its child controls.

Dispose enables a server control to perform a final cleanup operation before it is freed from memory.

Equals (inherited from Object) has been overloaded. Determines whether two instances of Object are equal.

FindControl has been overloaded. Searches for the specified server control in the current naming container.

GetHashCode (inherited from Object) serves as a hash function of a specific type, and is suitable for use in hashing algorithms and data structures such as a hash table.

GetType (inherited from Object) gets the Type of the current instance.

Hascontrols determines whether the server control contains any child controls.

RenderControl outputs the contents of the server control to the provided HtmlTextWriter object, and if tracing is enabled, stores trace information about the control.

resolveurl resolves a relative URL to an absolute URL based on the value passed to the TemplateSourceDirectory property.

ToString (inherited from Object) returns a String representing the current Object.

Public events:

DataBinding occurs when a server control is bound to a data source.

Disposed occurs when a server control is freed from memory, which is the last stage of the server control lifetime when the page is requested to be asp.net.

Init occurs when a server control initializes, and initialization is the first step in the lifetime of the control. server controls should perform any initialization steps required to create and set up an instance. The view state information cannot be used within the event; No other server control should be accessed during the lifetime of the event, whether it is a child or a parent of this control. It is not necessarily possible to create additional server controls or access them.

Load occurs when the server control is loaded into the Page object. Notifies the server control to perform any processing steps that are set to occur on each page request. The developer can access the view state information and use the event to form POST data. You can also access other server controls within the page control hierarchy.

PreRender occurs when the server control is to be rendered to its contained Page object. Use this event to perform any updates before the server control renders the output to the page. Any changes to the view state of the server control can be saved during the lifetime of the event. The same changes made in the rendering phase are not saved.

Unload occurs when a server control is unloaded from memory.

Protected properties:

ChildControlsCreated gets a value indicating whether the child controls of the server control have been created.

The context gets the HttpContext object associated with the server control for the current WEB request.

Events gets the list of event handler delegates for the control. This property is read-only.

Haschildviewstate gets a value that indicates whether the child controls of the current server control have any saved view state settings.

isTrackingViewState gets a value that indicates whether the server control saves changes to its view state.

ViewState gets a dictionary of state information that enables you to save and restore view state of a server control across multiple requests on the same page.

Viewstateignorescase gets a value that indicates whether the StateBag object is case-insensitive.

Protected methods:

AddParsedSubObject notifies the server control that an element (XML or HTML) has been parsed and adds the element to the server control's ControlCollection object.

Clearchildviewstate deletes view state information for all child controls of a server control.

CreateChildControls notifications use server controls that are based on a composite implementation to create any child controls they contain to prepare for postback or rendering.

Createcontrolcollection creates a new ControlCollection object to hold the child controls of the server control, including text controls and server controls.

EnsureChildControls determines whether the server control contains child controls. If not, the child control is created.

Finalize (inherited from Object) has been overridden. Allows object to attempt to free resources and perform other cleanup operations before garbage collection reclaims Object.

Isliteralcontent determines whether the server control contains only textual content. The normal HTML tags in the asp.net page are asp.net compiled into a literalcontent control (meaning lightweight controls).

LoadViewState Restore view state information from the previous page saved by the SaveViewState method.

Mappathsecure retrieves the mapping physical file path relative to the source file if the requesting server control has sufficient security permissions to read the mapping results.

MemberwiseClone (inherited from Object) creates a shallow copy of the current object.

OnBubbleEvent determines whether the event of a server control is passed up along the page's UI server control hierarchy.

OnDataBinding raises the DataBinding event.

OnInit throws an Init event.

OnLoad raises the Load event.

OnPreRender raises the PreRender event.

OnUnload raises the Unload event. Note at this stage of the server control lifetime, the server control should perform all the last cleanup operations, such as closing the file, shutting down the database connection, and discarding the object.

RaiseBubbleEvent assigns all event sources and their information to the control's parent.

Render sends server control content to the provided HtmlTextWriter object, which writes what will be rendered on the client.

RenderChildren outputs the contents of the server control's child to the provided HtmlTextWriter object, which writes the content that will be rendered on the client.

SaveViewState saves any server control view state changes that occurred since the page was sent back to the server.

TrackViewState causes a change in the view state of the tracking server control so that the changes can be stored in the StateBag object of the server control. This object can be accessed through the Control.ViewState property.


Here we rewrite the Render method to display the contents of the control through the HtmlTextWriter object.

Namespace Selfwebcontrol
{public
  class Controla:control//control class defines properties and methods that are shared by all ASP.net server controls
  {
    protected override void Render (HtmlTextWriter writer)
    {
      writer. Write ("<table style= ' width:300px; height:200px; Background-color:bisque ' > ');
      Writer. Write ("<tr>");
      Writer. Write ("<td> This is the first column </td>");
      Writer. Write ("<td> This is the second column </td>");
      Writer. Write ("<td> This is the third column </td>");
      Writer. Write ("</tr>");
      Writer. Write ("</table>");}}

When we build our Selfwebcontrol project, and then switch to the ASP.net application's toolbox, VS2008 automatically adds the ControlA we just created to the toolbox, avoiding the process of adding controls previously by selecting items.

In this way, we have implemented a ASP.net server control in the simplest form. But what if I want to change the width of the table, the height, the background color?

This requires that we define the properties of the server control. As we all know, ASP. NET server control has many properties, and our current control has only a few public properties.

Let's take a look at the changes we made:

The public class Controla:control//control class defines the properties and methods that are shared by all ASP.net server controls {private int _twidth;
    private int _theight;

    
    private string _bgcolor; [Browsable (True)]//is visible in the Properties window [Category ("appearance")]//attributes of the classification, such as behavior, appearance, you can see this classification in the Properties window [DefaultValue (100)]//
      The default value of the property [Description (table width)]//These are public int Twidth {get {return _twidth] displayed under the Properties window;
    set {_twidth = value;} [Browsable (True)] [Category ("appearance")] [DefaultValue (m)] [Description ("table height")] public int the
      ight {get {return _theight;}
    set {_theight = value;} [Browsable (True)] [Category ("appearance")] [DefaultValue ("Bisque")] [Description ("Table background color")] public
      String bgcolor {get {_bgcolor;}
    set {_bgcolor = value;} } protected override void Render (HtmlTextWriter writer) {writer. Write ("<table style= ' width:" + twidth + "PX; Height: "+theight+" PX; Background-color: "+BGColor+ "' >"); Writer.
      Write ("<tr>"); Writer.
      Write ("<td> This is the first column </td>"); Writer.
      Write ("<td> This is the second column </td>"); Writer.
      Write ("<td> This is the third column </td>"); Writer.
      Write ("</tr>"); Writer.
    Write ("</table>"); }
  }

The code is very simple, presumably everyone can understand, it is worth noting that the declaration of each attribute. Need to reference namespaces: using System.ComponentModel; the function of each tag I've already explained in the code, so we've added attributes to our controls.

It's also important to add the following code if we want to automatically add some properties to the label when we drag the control onto the page:

Copy Code code as follows:

[ToolBoxData ("<{0}:controla runat= ' server ' bgcolor= ' red ' theight= ' twidth= ' ' ></{0}:ControlA>")]

It is noteworthy that the wording here, {0} after the colon in the "ControlA" is the name of the class, do not write wrong. and runat= ' Sever ' must be written.

is not very simple, so that we simply encapsulate the simple HTML to complete the production of the ASP.net control.

Summary: Simple to make a ASP.net server control is very simple, but the light is only through the output of HTML sometimes not very meaningful, here is only a way and ideas. Open the first door to learn to customize your own asp.net control. In a future article I'll introduce needles to develop asp.net controls for inherited WebControl.

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.