ASP. NET component design step by step (1-3)
Transferred from csdnblog's cashcho Column
Learn how to create a project library and apply it in your own project
1. Start vs200x
2. Select New Solution
3. Select the default solution type and the web control library. The web control library does not need a web site. It is basically a dll library.
4. Enter the name of your type library, such as aspctllib. This determines the namespace and the name of the referenced database used by other projects in the future.
5. The code automatically generated by the system is as follows:
Using system;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Using system. componentmodel;
Namespace aspctllib
{
/// <Summary>
/// Summary of webcustomcontrol1.
/// </Summary>
[Defaultproperty ("text "),
Toolboxdata ("<{0}: webcustomcontrol1 runat = server ></ {0}: webcustomcontrol1>")]
Public class webcustomcontrol1: system. Web. UI. webcontrols. webcontrol
{
Private string text;
[Bindable (true ),
Category ("appearance "),
Defaultvalue ("")]
Public String text
{
Get
{
Return text;
}
Set
{
TEXT = value;
}
}
/// <Summary>
/// Present the control to the specified output parameter.
/// </Summary>
/// <Param name = "output"> HTML writer to be written </param>
Protected override void render (htmltextwriter output)
{
Output. Write (text );
}
}
}
6. Introduction to assemblyinfo. CS
7. Compile this project to obtain aspctllib. dll.
8. Other project references
How to reference a self-built web control library
1. Open/create an Asp.net Project
2. When aspctllib. dll is referenced, aspctllib will appear in the reference, and the previous DLL file will be copied to the directory of the current project.
3. Add the controls in your web control library to the toolbar tab: Right-click the tab, customize the toolbox, and select. NET framework component, browse, find aspctllib. after adding DLL, you can see that the component named webcustomcontrol1 exists in the toolbox
4. Open your own aps.net web project and select a web form to add your own controls to it. By default, this control displays [webcustomcontrol1 "webcustomcontrol1"].
5. Select the control in the form and open the property to edit it. Basically, the default design control has only one text property, which is a custom property. Enter specific text.
-------------------------------------------------------------------------------
ASP. NET Component Design (2)
In terms of inheritance relationships, Asp.net server controls are classified into four categories:
1. User Control
Similar to page, there is basically no need to program. You can use An ASPX page as a reusable component.
2. literalcontrol
ASP. NET compiles all HTML elements and readable text that do not need to be processed by the server into an instance of this class. For example, HTML elements that do not contain runat = "server" attribute/value pairs in the start tag are compiled into literalcontrol objects.
The behavior of the text control is the same as that of the text control, which means that the text control can be extracted from the text control and removed from the controlcollection of the parent server control through the CONTROLS attribute of the parent Server Control. Therefore, when developing custom controls exported from the literalcontrol class, make sure that the control executes any required preprocessing steps by itself, rather than implementing them by calling the literalcontrol. Render method. This is generally done to increase the response time of Web applications.
Literalcontrol generally does not trigger server events.
You can use the controlcollection. Add or controlcollection. Remove methods to add or remove text controls from pages or server controls programmatically.
3. htmlcontrol
The Asp.net model server component of the HTML element. Each htmlcontrol corresponds directly to a specific HTML element (not necessarily an input element ).
4. webcontrol
Common Web controls. It can be understood as a complex HTML element and a server-side processing logic.
Inheritance relationship diagram:
System. Object
System. Web. UI. Control
System. Web. UI. templatecontrol
System. Web. UI. Page
System. Web. UI. usercontrol
System. Web. UI. literalcontrol
System. Web. UI. htmlcontrol
System. Web. UI. webcontrol
Generally, users and Web controls must be developed by programmers. Xxx
Web Server Components inherited from webcontrol often inherit rich UI elements and control capabilities.
User Control
1. Why is it a user control?
Modern people prefer to be lazy, "What you see is what you get", and "drag-and-drop" programming. A shared UI, such as header footer, usually exists in multiple pages in an Asp.net web project. If the content of all pages is consistent, it is often implemented by using specific JS files. However, if the UI parts required for these pages are different depending on different user statuses, dynamic logic must be adopted, common JavaScript/html cannot meet the requirements. Previously, ASP was implemented using the include ASP file. Now Asp.net has changed various limitations including ASP files and uses user controls to solve them.
The user control is essentially an independent Asp.net file with the extension ascx. User Controls usually depend on specific Asp.net web projects. When a user control is used, the Asp.net page parser dynamically generates a class from the aspx file, compiles it to a specific assembly (a DLL is hosted in the temporary cache), and.. net.
2. How to obtain the user control
To obtain the user control, in Vs, you only need:
In the WEB Project, add-> User Control-> enter the user control name-> on the blank page, perform the uidesign and store.
You can drag and drop the user control on a web form to use the user control. In this case, vs replaces us with the following:
Add a register command on the page using the user control. Specifically:
<% @ Register tagprefix = "uc1" tagname = "webusercontrol1" src = "webusercontrol1.ascx" %> the page interpreter interprets <uc1: webusercontrol1 as a user control, uc1 is the tag prefix (similar to the ASP tag prefix of a standard web control), and webusercontrol1 is the tag of this user control. In this combination, it is interpreted as using the user control instance. The SRC value is the virtual path of the user control source file, but cannot be an absolute path.
3. essence of User Controls (background of user controls in Asp.net)
Asp.net is compiled. processing user controls is similar to processing pages. All elements on the pages are compiled into specific classes and called and triggered by the Asp.net page class. User Controls are also reused in this way. When processing user controls, the page framework performs the following steps:
Interpret the ascx file as a Managed class derived from system. Web. UI. usercontrol
Dynamically compile to auto-generated accessories.
The above process only occurs when the user control is used for the first time. Subsequent reuse of this user control will omit this step. This class will be referenced when you use the register command on the page. User Controls on the page will become instances of this type. In fact, user controls are also the Asp.net class, derived from system. web. UI. usercontrol class, the use of these classes on the page is like the standard class using Asp.net, for different standard control class built-in can be directly instantiated for use, the user control needs to compile similar pages before use. After compiling the class and assembling it into the assembly, it can be instantiated.
4. User Control Programming considerations
User components cannot be instantiated using the new method, because the user control class is dynamically generated and new (this should be the time when the page is compiled and the user control is not run yet ), the user control class does not exist. However, you can use page. loadcontrol (string controlname) is used for loading. In this case, the refence command is used to locate the user control for loadcontrol: <% @ refence control = "xxx/usercontrolsamples. ascx "%>.
User Controls can be nested by other user controls, but must be correctly referenced.
The user control itself belongs to the UI and can be cached. It is determined by the outputcache command at the top of the ascx file.
The URL in the user control code refers to the path in which the user control exists, rather than calling the Page code path of the user control. You must use page. resolveurl for correct parsing.
Bytes -------------------------------------------------------------------------------------
ASP. NET Component Design (3)
Getting started with custom controls
The component that executes program logic on the server side is the basic construction block of the Asp.net application. Certain conditions must be met for execution in the Asp.net environment.
To be able to participate in the execution of the webpage framework, the icomponent, idisposable, iparseraccessor, idatabindingsaccessor, and other interfaces must be met. Therefore, the Framework provides the system. Web. control class for control developers to inherit.
Icomponent provides the basic functions required by the component. The interface implementation is:
{
Isite site {Get; set;} // provides the site interface through which components can access the container
Event eventhandler disposed; // event
} If this interface is implemented, it becomes a component that can be designed. You can add it to the visualization Designer toolbox and put it off the page (isite Interface) to display properties in the property browser.
The idisposable interface is used to release component resources (icomponent actually inherits from idisposable)
Iparseraccessor this interface specifies that the addparsedsubobject (Object OBJ) method is used to notify the Server Control of the analyzed elements (XML or HTML ). When analyzing an element, the element is recognized as a child of the server control that implements this interface. These elements are converted to objects. When this interface is implemented, the created control immediately defines the processing to happen after being notified of the analyzed elements.
The idatabindingsaccessor interface allows you to access the data binding expression set of the control during design.
{
Databindingcollection databindings {Get;} // indicates the collection of all data bound to the control. This attribute is read-only.
Bool hasdatabindings {Get;} // whether the return control contains any data binding logic.
}
The webcontrol class inherited from control represents HTML (after all, the user sees html) and adds some new functions to the control class, such as style, Font, background, and foreground...
Definition of 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.
Common Methods
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 and methods include:
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.