ASP. NET custom Control

Source: Internet
Author: User

In Visual Studio, all of the ASP. NET 2.0 controls are custom controls, and creating your own custom controls typically requires the following three steps to complete.
(1) Create a new class under the site App_Code;
(2) Modify this class to make it a derived class of the WebControl class (contained in the System.Web.UI.WebControls namespace);
(3) overriding the RenderContents () method of the base class (that is, the WebControl class).

Here is one of the simplest ASP. NET control, it has only one function, display "Hellow world".

Using System;

Using System.Web.UI;

Using System.Web.UI.WebControls;

Namespace MyControls


public class Helloworld:webcontrol


protected override void RenderContents (HtmlTextWriter writer)


Writer. Write ("Hello World");



After the custom control is created, there are three ways to add it to the Web page.
The first option is to first add the code that registers the control in the ASPX file:

<%@ Register tagprefix= "Custom" namespace= "MyControls"%>
Where the value of the TagPrefix property is arbitrarily selected, the value of the namespace property must be the same as the custom control you create, and you can reference the control anywhere on the page.

<custom:helloworld id= "HelloWorld1" runat= "Server"/>
The second option is to register the control in the Web. config file so that you can reference the control in all the ASPX pages. The relevant configuration is as follows:



<add tagprefix= "Custom" namespace= "MyControls"/>


The last way is to add the control to the Visual Studio Toolbox and drag it directly to the Web page when you use it. But this time you cannot create this control under the App_Code folder, but you must create it as a standalone assembly, as described later in this article. After you create a standalone custom control, right-click the Visual Studio Toolbox, select Select Item, and a dialog box pops up to select your own assembly, and the custom control will automatically appear on the toolbox.

Embed JavaScript

To get a better client effect, we need to introduce JavaScript and CSS stylesheets. In ASP. NET, there is a class called ClientScriptManager, which makes it easy to manipulate JavaScript, and the more important methods are:

    • RegisterClientScriptBlock ()
    • RegisterStartupScript ()
    • RegisterClientScriptInclude ()
    • GetWebResourceUrl ()

The RegisterClientScriptBlock and RegisterStartupScript methods allow you to add built-in JavaScript scripts to your Web pages, both of which are typically used to add simpler JavaScript scripts. If you need to add a complex JavaScript script, you can use the RegisterClientScriptInclude or GetWebResourceUrl () method. The RegisterClientScriptInclude () method will include such a reference in the Web page:

<script type= "Text/javascript" src= "Somescript.js" ></script>
The disadvantage of this approach is that the release of the program when the separate JS files need to be published together, the solution to this problem is to use the GetWebResourceUrl () method, through this method can be directly embedded JS file into the control, In other words, the assembly you publish will contain both the custom control and the standalone JS file. As with the previous registration control, custom controls created in App_Code cannot contain both JS files and need to be published as separate assemblies.
First we create a new project in Visual Studio, type select Class library. In order to create a custom control in a class library project, you first need to add a reference to the SYSTEM.WEB.DLL, then select the JS file in the project and modify its build event property to embed the resource. Next you need to add the WebResource attribute to each embedded resource in AssemblyInfo, just open the AssemblyInfo.cs file in the properties and add the following code:

[Assembly:webresource ("WhoIsLooking.WhoIsLooking.js", "Text/javascript")] The calling code for the JS file in the OnPreRender () method:

ADD Javascript include

String Scripturl = Page.ClientScript.GetWebResourceUrl (this. GetType (),


Page.ClientScript.RegisterClientScriptInclude ("whoislooking", Scripturl);

Embed CSS style sheets

method is similar to embedding JavaScript, and is added in AssemblyInfo.cs:

[Assembly:webresource ("WhoIsLooking.WhoIsLooking.css", "Text/css")]
In the OnPreRender method, add:

ADD style sheet to parent page

String cssurl = Page.ClientScript.GetWebResourceUrl (this. GetType (),


Htmllink Csslink = new Htmllink ();

Csslink.href = Cssurl;

CSSLINK.ATTRIBUTES.ADD ("rel", "stylesheet");

CSSLINK.ATTRIBUTES.ADD ("type", "text/css");


ADD class Name

This. CssClass = "whoislooking";

Using Ajax

The Whoislooking control uses AJAX technology to display visitor information in real time, and Ajax is the abbreviation for asynchronous JavaScript and XML, which enables data transfer between the client and server side without refreshing the entire page. To implement Ajax in an ASP. NET custom control, you need to complete the following three steps:
1 initiate client requests using getcallbackeventreference ();
2 implements the ICallbackEventHandler interface in response to the client's request, which has two methods that need to be implemented: the RaiseCallbackEvent () method and the GetCallbackResult () method.
3 Create a JavaScript client function to get the returned data and take the appropriate action.

Whoislooking the request is initiated every 5 seconds, add the following code to the OnPreRender () method:

String callback = Page.ClientScript.GetCallbackEventReference





String.Format ("' {0} '", this. ClientID),



String startupscript = String.Format ("setinterval (/" {0}/", {1});", Callback, _pollinginterval * 1000);

Page.ClientScript.RegisterStartupScript (this. GetType (), "whoislooking", Startupscript, True);
Next you need to rewrite the raisecallbackevent () and GetCallbackResult () methods, and the RaiseCallbackEvent () method will add the current user to the guest list and also remove the left user from the list. GetCallbackResult () returns information about the visitor, including user account number, name, dwell time, browser information, hostname, operating system information, etc. The return value of the method is a JSON array, which is the standard format for the information represented in the AJAX request (for a more introduction to JSON, please visit For example, if you have two users browsing the current Web page at the same time, the JSON value will look like this:

[{userId: "Fooglm45cjcycw55qi4yluvk", UserName: "Superexpert//steve", Duration: "0 minute (s)", browser: "IE 7.0", RemoteHost: "", Platform: "WinXP"},{userid: "1kqatn55sxc4vi55ummxghil", UserName: "superexpert//Bill" , duration: "0 minute (s)", browser: "Firefox", RemoteHost: "", Platform: "WinXP"}]
Finally, the Whoislooking control displays user information on the client through the Updatedisplay () method, which creates a <div> layer for each user to hold user information.

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: 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.