ASP. NET custom control development example (1)

Source: Internet
Author: User

This article describes the control development by implementing a server control. The functions of this control are as follows:
1. display the server time and keep updating
2. Manually click the refresh button to obtain the server's latest time using Ajax.
3. Drag
4. Remember the location on the page. The location remains unchanged after the page is returned.
5. You can configure a scheduled time. At this time, auto-return will trigger user-defined events.

First create a class library project hampwebcontrol, and then create a class named tiptime1 to inherit the webcontrol class. If it is not inherited from an existing control, it generally inherits the webcontrol class,
It is the base class of all ASP. NET Server controls.

Compile this project, create a new website project, reference the hampwebcontrol project, create a page, and drag a tiptime1 control in the toolbox to the page.

When we run this page, we will find the htmlCodeAs follows:

That is to say, the tag is displayed as a span tag by default, which can be changed by reloading the tagkey attribute of the webcontrol base class.

This is a div displayed on the page. Htmltextwritertag is an enumeration that contains many HTML tags.

The render of the basic webcontrol class is used to render the content. You can reload it to render any custom labels on the page.

A tag a is displayed on the page, as shown in:

Note: At this time, the tag is outside the Div. How can I put it inside the div? This requires reload the rendercontents method of the webcontrol base class.

In this way, the tag is in the DIV, as shown in:

Next, add some styles to the peripheral Div and reload the addattributestorender method of the base class.

There are two ways to use them: Use htmltextwriterstyle to enumerate or directly write the CSS attribute name.

Now you know how custom controls are displayed on the page. Create another class tiptime2, reload the tagkey as Div, and then reload rendercontents,
Displays a span tag and an input tag.

 

 

In this way, the current server time and a button are displayed ,:
Next, let the user configure the text on the button to add a text attribute for the tiptime2 class:

At the same time, change the code of the rendering button:

In this way, the text attribute appears in the design view attribute window.

Modify the text value. The text on the buttons on the page also changes. Note that the text attribute is stored in viewstate, which ensures that the value will not be lost after sending back.
Now the problem is that time does not change. We need JavaScript to change its value. Create a new JS file, tiptime2.js.
It should be noted that the project already has a JS file _ webcontrolbase. JS, which contains some common JS methods, such as binding events and obtaining control coordinates. All methods are
Extension Method of this method: var hampwebcontrol = function (){}

   ///   stop event bubbling   
hampwebcontrol. prototype. stopbubble = function (E) {
If (E && E. stoppropagation) {
E. stoppropagation ();
} else {< br> window. event. cancelbubble = true ;
}< BR >}

In this way, global variables can be reduced and names of variables in other JS codes can be avoided as much as possible. I use each control as an extension method of the hampwebcontrol method.
An array is used to store all the JS objects of the control on the page. Each control corresponds to a refresh method to re-bind events. This is to solve the problem after the return.


The structure of the control displayed as HTML is <div> <SPAN/> <input/> </div>, which has three tags, we need to use three variables to store their DOM objects separately for future operations.

When naming HTML tags in the background, it starts with the clientid of the current control, followed by a suffix as needed, which can prevent duplicate tags to some extent. The console transmits the clientid of the control,
In this way, all DOM objects can be obtained. The drag effect uses the ready-made js method, which is a pure JavaScript effect. We will not discuss it here. If you are interested, you can view the source code of the sample project.

This method is called by the background registration script. if it already exists in the array, this object is taken; otherwise, a new one is created. And call the initialization and binding event method.
You need to register the JS file in the background. During key operations, set the "generate operation" attribute of the file to "embedded resources" so that the JS file will be part of the DLL file during compilation.

Next, declare the required resource file and name it strictly according to the folder structure. Here two JS files are registered: Public JS file _ webcontrolbase. js and control-specific JS file tiptime2.js.

Then register the script in the code.

In the book "Dao is not far away from in-depth analysis of ASP. net2.0 control development", the code for registering a script file is stored in the onprerender method, but in actual application, I found that
When the control is placed in the updatepanel control, it will cause some problems, so I will register the script file in the onload method.
Note that two different methods are used to register the script file.
The first type is whether there is a script in the loop head tag. If not, insert a <SCRIPT> tag.
2nd methods for directly calling. Net Registration.

   ///     <Summary>  
/// Register a public jacascript file with the page
/// </Summary>
/// <Param name = "control"> Control Object </Param>
Internal Static Void Registercommonjsfile (Control)
{
// Register the jacascript File
String jslink = " <SCRIPT src =' " +
Control. Page. clientscript. getwebresourceurl (control. GetType (),
" Hampwebcontrol. nodes. _ webcontrolbase. js " )
+ " 'Type = 'text/JavaScript '> </SCRIPT> " ;
Register (jslink, control );
}

/// <Summary>
/// Register Resources
/// </Summary>
/// <Param name = "strlink"> Resource string </Param>
Private Static Void Register ( String Strlink, Control)
{
// To ensure that resources are registered only once and compared cyclically, if resources already exist, they are not added.
Boolean flag = False ;
For (Int32 I = 0 ; I < Control. Page. header. Controls. Count; I ++ )
{
Literalcontrol LC = Control. Page. header. controls [I] As Literalcontrol;
If (LC ! = Null )
{
If (LC. Text = Strlink)
{
Flag = True ;
Break ;
}
}
}
If ( ! Flag)
{
Literalcontrol include = New Literalcontrol (strlink );
Control. Page. header. Controls. Add (include );
}
}

1st types are used to register public resource files, and 2nd types are used to register resource files specific to the control. Because the 2nd method can only ensure that only one script is registered for multiple control objects, but other controls cannot
The script is registered repeatedly. To ensure that the public resource file is registered only once, 1st methods are used.
The next step is to register the script code to be executed:

If the control is hidden, it is not registered. In fact, if the control is placed in other container controls, such as panel, and the parent container control is set to hide, the control is invisible, but the above script is still registered
Code, so you need to determine whether the corresponding DOM object exists in the init method at the front end, there is no more judgment here.
Finally, set the style to change it to floating, and the control can be dragged on the page.

Here we will summarize how to present custom controls, add attributes, and add resource files. The next section describes how to call Ajax and implement custom events.

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.