ASP. NET Server Control development (1) encapsulated html and asp.net controls

Source: Internet
Author: User
Tags form post

ASP. NET Server Control development (1) encapsulated html and asp.net controls

In our project development, due to the limited functions of ASP. NET Server controls, we often define specific server controls to meet specific business requirements in development. It can be seen that it is necessary to know How to Develop ASP. NET Server controls.

In fact, the simple implementation of ASP. NET Server Control is not very difficult. In the past, Daniel introduced the relevant content in the garden. Here, I am standing on the shoulders of giants to share and Develop ASP. NET Server control methods and some of your own experiences. Write it to the novice, and the experts will bypass it.

Learning ASP. NET Server Control Development, I personally think that the best way is to practice, of course, theoretical knowledge is also very important, but if we only look at the theoretical knowledge, it may be confused by some of the concepts in it. When you look at it, you will fall asleep. If you create your own control, the effect will be different.

The following describes how to create a simple server control through an instance:

First, we create a class library project SelfWebControl. In the same solution, we create an ASP and NET Web application (used to test our controls)

Namespace SelfWebControl {public class ControlA: Control // The Control class defines the attributes and Methods shared by all ASP. NET Server controls {}}

I inherited the ControlA class from the Control class. The Control class is the base class of all controls in. NET, which contains the attributes and Methods shared by controls.

Control class

Public attributes:

ClientID gets the Server Control identifier generated by ASP. NET.

Controls gets the ControlCollection object, which indicates the child control of the specified server control in the UI hierarchy.

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

ID.

NamingContainer gets a reference to the name container of the server Control. This reference creates a unique namespace to distinguish the server Control with the same Control. ID attribute value.

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 to obtain information about the Web site to which the server control belongs (originally from MSDN, but I don't think so. It should be the "Container" Site of the component, not the web site ).

TemplateSourceDirectory: Obtain the virtual directory of the Page or UserControl that contains the current server control.

UniqueID obtains the unique identifier of the server control in hierarchical form.

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

Public method:

DataBind binds the data source to the called Server Control and all its child controls.

Dispose allows the Server Control to perform the final cleanup operation before being released from the memory.

Equals (inherited from Object) is overloaded. Determine whether the two Object instances are equal.

FindControl is overloaded. Search for the specified server control in the current named container.

GetHashCode (inherited from an Object) is used as a hash function of a specific type. It is applicable to hash algorithms and data structures (such as hash tables.

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

HasControls determines whether the server control contains any child control.

RenderControl outputs the content of the server control to the provided HtmlTextWriter object. If the tracking function is enabled, the tracking information about the control is stored.

ResolveUrl resolves the relative URL to an absolute URL based on the value passed to the TemplateSourceDirectory attribute.

ToString (inherited from Object) returns the String of the current Object.

Public events:

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

Disposed occurs when the server control is released from the memory. This is the final stage of the server control survival when ASP. NET pages are requested.

Init occurs when the server control is initialized. Initialization is the first step of the control's survival. The server control should perform any initialization steps required to create and set instances. View status information cannot be used in this event; it is not filled yet. Other server controls should not be accessed during the lifetime of the event, whether it is a child or parent level of the control. Other server controls may not be created or accessed.

Load occurs when the server control is loaded to the Page object. Notify the Server Control to perform any processing steps that are set to occur each page request. Developers can access view status information and use this event to form POST data. You can also access other server controls in the page control hierarchy.

PreRender occurs when the server control is to be rendered to the Page object it contains. Use this event to execute any updates before the Server Control displays the page output. During the lifetime of the event, you can save any changes to the server control view status. Do not save the same changes made during the rendering phase.

Unload occurs when the server control is detached from the memory.

Protected attributes:

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

Context is the HTTP Context object associated with the server control for the current Web request.

Events obtains the event handler delegate list of the control. This attribute is read-only.

HasChildViewState gets a value that indicates whether the child control of the current server control has any saved view status settings.

IsTrackingViewState gets a value that indicates whether the server control saves changes to its view status.

ViewState: A Dictionary of State information that allows you to save and restore the view State of the server control between 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 analyzed in syntax and added to the ControlCollection object of the server control.

ClearChildViewState deletes the view status information of all child controls of the server control.

CreateChildControls notifies you to create any child controls they contain using the server controls implemented based on synthesis to prepare for sending back or rendering.

CreateControlCollection creates a new ControlCollection object to save child controls of server controls (including text controls and server controls ).

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

Finalize (inherited from Object) has been rewritten. Allow objects to try to release resources and perform other cleanup operations before they are recycled.

IsLiteralContent determines whether the server control only contains text. The common html tag on the Asp.net page is compiled into a LiteralContent control (meaning a lightweight control) by asp.net ).

LoadViewState requests to restore the view status information from the previous page saved by the SaveViewState method.

MapPathSecure: if the request Server Control has sufficient security permissions to read the ing result, retrieve the mapped physical file path relative to the source file.

MemberwiseClone (inherited from an Object) creates a superficial copy of the current Object.

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

OnDataBinding triggers a DataBinding event.

OnInit triggers the Init event.

OnLoad triggers the Load event.

OnPreRender triggers the PreRender event.

OnUnload triggers the Unload event. Note that during this stage of server control survival, the server control should perform all final cleanup operations, such as closing files, closing database connections, and dropping objects.

RaiseBubbleEvent assigns all event sources and their information to the parent level of the control.

Render sends the server control content to the provided HtmlTextWriter object, which is written in the content that will be presented on the client.

RenderChildren outputs the child-level content of the server control to the provided HtmlTextWriter object, which is written in the client.

SaveViewState saves any server control view status changes that occur after the page is sent back to the server.

TrackViewState causes the trail to change the view status of the server control so that these changes can be stored in the StateBag object of the server control. You can access this object through the Control. ViewState attribute.


Here we will rewrite the Render method to display the content in the control through the HtmlTextWriter object.

Namespace SelfWebControl {public class ControlA: Control // The Control class defines all ASP. NET server controls shared properties and methods {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> ");}}}

Generate the SelfWebControl project and switch to ASP. NET application toolbox, VS2008 will automatically add the ControlA we just created to the toolbox, avoiding the previous process of adding controls by selecting items.

In this way, we have implemented an ASP. NET Server Control in the simplest form. But how can I modify the width, height, and background color of a table?

This requires us to define the properties of the server control. As we all know, ASP. NET Server controls have many attributes, and our current controls only have several public attributes.

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

Public class ControlA: Control // Control class defines all ASP. NET Server Control shared properties and methods {private int _ tWidth; private int _ tHeight; private string _ bgColor; [Browsable (true)] // whether the [Category ("Appearance")] is visible in the attribute window // The attribute Category, such as, behavior, Appearance, you can see this category in the Properties window [DefaultValue (100)] // default attribute value [Description ("table width")] // These are public int tWidth {get {return _ tWidth;} set {_ tWidth = value ;}} [Browsable (true)] displayed under the Property Window. [Category ("Appearance")] [DefaultValue (100)] [Description ("table height")] public int tHeight {get {return _ tHeight ;} set {_ tHeight = value;} [Browsable (true)] [Category ("Appearance")] [DefaultValue ("Bisque")] [Description ("")] public string bgColor {get {return _ 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 and can be understood by everyone. It is worth noting that each attribute is declared. You need to reference the namespace: using System. ComponentModel; I have already explained the role of each label in the Code, so that we have added properties for our controls.

It should also be noted that if we want to automatically add some attributes to the tag when dragging the control to the page, we need to add the following code:

Copy codeThe Code is as follows:
[ToolboxData ("<{0}: ControlA runat = 'server' bgColor = 'red' tHeight = '000000' tWidth = '000000'> </{0 }: controlA> ")]

It is worth noting that the "ControlA" after the colon of {0} is the name of the class. Do not make any mistakes. And runat = 'sever 'must be written.

Is it easy? In this way, we only encapsulate simple html to complete the production of ASP. NET controls.

Summary: simple production of an ASP. NET Server Control is very simple, but it is of little significance only through html output. Here is just a method and train of thought. Open the first door to learn how to customize your own ASP. NET control. In future articles, I will introduce the development of ASP. NET controls for inheriting 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.