[Reprint]
Download the original English version and code:
Http://aspnet.4guysfromrolla.com/articles/080906-1.aspx
Use webresource. axd to access the built-in resources of accessories through a URL
Introduction:
Many ASP. net server controls all require additional external resources to implement certain functions. for example, use any ASP. net validation controls, a series of JavaScript Functions are required to perform their client verification. although you can add these JavaScript Functions on the page, the more efficient way is to encapsulate these functions in an external Javascript file, then, the file is included in the page in the form of <SCRIPT src = "pathtoexternaljavascriptfile" type = "text/JavaScript">. this not only reduces page size, but also allows the browser to cache the Javascript file (so that each page does not need to send the JavaScript code to the browser at login/back-transmission)
In ASP. before NET 2.0, If your browser wants to access such external resources, we must put them as specific files in the file system. if you use ASP. net 1. X verification control, you must add a reference to the Javascript file on your page, such as/aspnet_client/system_web/version/webuivalidation. JS. these external files impede the final deployment.
To solve this problem, Asp. NET 2.0 allows external resources to be embedded into the widget's accessories and accessed through a specified URL. it is easy to deploy external images, JavaScript files, and CSS files after the components are embedded in the control, because all resources are included in. DLL file. after the implantation is completed. on the Net 2.0 page, we can use a specified URL (webresource. axd) to access these resources.
This article describes how to implant external resources into accessories and how to access them through a specified URL, which simplifies installation and deployment.
Example of a custom control...
To evaluate ASP. NET 2.0, we need to build a custom control that contains external resources. in this article, I will create a simple control to expand the basic functions of the Textbox Control. the control-funkytextbox is used to randomly change the background color of the textbox in the onkeypress event of the client using the color defined in the color array.
This behavior requires some client scripts: first, we need to add a function to obtain a random number, and then set the background color of textbox Based on the random number. second, we need to define the color array to be used. we can easily bypass external files and directly inject Javascript to the page. the following code shows the complete code of the funkytextbox control (for simplicity, the using declaration, namespace, And the defined colors array are omitted)
Public class funkytextbox: textbox
{
Protected override void addattributestorender (system. Web. UI. htmltextwriter writer)
{
// Wire up the onkeypress event handler to the changebackgroundcolor () JavaScript function
Writer. addattripress ("onkeypress", "changebackgroundcolor (this );");
Base. addattributestorender (writer );
}
Protected override void onprerender (eventargs E)
{
// Dump in the Javascript directly into the page
// (Although the external JavaScript approach is more efficient)
Page. clientscript. registerclientscriptblock (this. GetType (), "funkytextbox ",
@"
Function changebackgroundcolor (CTRL)
{
VaR rndnum = math. Floor (math. Random () * 256 );
If (CTRL & funkytextboxcolors. length> rndnum)
CTRL. style. backgroundcolor = funkytextboxcolors [rndnum];
}
VaR funkytextboxcolors = new array ('#89c142', '# ef14e5', '# 75762c', '# bb9e24', '# bf4a44 ', '#9d4a77 ',...);
", True );
Base. onprerender (E );
}
}
The server control inherits from ASP. net Textbox, override two methods. first, a client-side attribute is added to the addattributestorender method. When you type a character in the Textbox Control, call the JavaScript function named changebackgroundcolor to pass in a reference to the textbox. second, in the prerender event of funkytextbox. the clientscript class's registerscriptblock method directly injects the required Javascript into the page. specifically, the changebackgroundcolor function and funkytextboxcolor arrays are defined, while changebackgroundcolor function obtains a random value, and then uses the corresponding color in the funkytextboxcolor array to set the background color based on the value.
After adding funkytextbox to an ASP. NET page, the final page will contain the following code:
<SCRIPT type = "text/JavaScript">
<! --
Function changebackgroundcolor (CTRL)
{
VaR rndnum = math. Floor (math. Random () * 256 );
If (CTRL & funkytextboxcolors. length> rndnum)
CTRL. style. backgroundcolor = funkytextboxcolors [rndnum];
}
VaR funkytextboxcolors = new array ('#89c142', '# ef14e5', '# 75762c', '# bb9e24', '# bf4a44 ', '#9d4a77 ',...);
// -->
</SCRIPT>
Here is a funkytextbox:
<Input onkeypress = "changebackgroundcolor (this);" name = "mytextbox" type = "text" id = "mytextbox"/>
The onprerender method is used to inject Javascript into the page, and the funkytextbox control is displayed as a <input type = "text"> flag. Its onkeypress event calls the changebackgroundcolor function.
Transfer JavaScript to an external file to slim down the page
The javascript used by the funkytextbox control is very simple. The javascript needed to implement its functions is far more complex than that. directly inserting Javascript into the page will increase the page size, which will also allow users to spend more time loading the page. to reduce page size, you should transfer JavaScript to an external file and add a <SCRIPT> tag to the page to reference Javascript file. For example:
<SCRIPT src = "pathtoexternaljavascriptfile" type = "text/JavaScript">
Replacing JavaScript with the <SCRIPT> element achieves the goal of page slimming. in addition, if the browser caches external files, we only need to download them once (if Javascript is directly implanted into the page, each page must be loaded upon login/loading)
In ASP. net 1. x. These external resource files, such as JavaScript files, CSS classes, and images, must be loaded and expanded together with custom control. in ASP. NET 2.0, We can implant these external resources into the widget accessories, and then access these resources through a specified URL.
Insert external files into the assembly of the control
To implant resources into components of controls, we need to add resources to your server control project in Visual Studio (downloadable code at the end of this article, contains funkytextbox Web Control Project and a test website ). for the funkytextbox control, I added a name named funky. JS file. The javascript contained in it is the Javascript that we injected into the page in the previous onprerender method ..
After adding, select it in Solution Explorer and open the Properties window. Set build action to "embedded resource", for example:
Figure
In this way, once you generate a solution, the file will be embedded into the final assembly.
Access Embedded Assembly through a URL
You can use webresource. axd HTTP handler to access these built-in resources. Use a URL, such as http: // yoursite/webresource. axd? D = assemblykey & t = datetimeoflastassemblywrite, where assemblykey is the encrypted string of the name of the accessories to be accessed, while datetimeoflastassemblywrite describes the Last modified Date of the accessories. given a valid assemblykey, then webresource. axd HTTP handler can return the content of built-in resources.
When using webresource. axd HTTP handler, we have to face three problems:
1. Use webresource. axd HTTP handler to allow access to a built-in resource.
2. Pass the exact querystring value to webresource. axd HTTP handler to retrieve a specific built-in Resource
3. Place the URL generated in step 1 on the ASP. NET page.
Webresource is not allowed by default. axd HTTP handler accesses the built-in Resources in the accessories. to rewrite this behavior, we must add an attribute to the assemblyinfo file of the server control project. Specifically, to add a webresource feature, for example:
[Assembly: webresource (webresource, contenttype, performsubstitution)]
Note: If you are using Visual Basic, you need to use "<" and ">" to restrict the installation of accessories, such as <Assembly: webresource (...)>. to view the assemblyinfo file, select "show all files" in Solution Explorer, which appears in the "My project" folder. Furthermore, the webresource feature is located in system. web. ui namespace, so we need to go to assemblyinfo. add using system at the top of the CS file. web. ui Declaration (if it is VB, use imports system. web. UI ).
The webresource parameter specifies the name of the resource to be accessed. The naming mode is rootnamespace. pathtofile. for this example, the root namespace is funkytextbox, and because the resource file is under the root directory of the project, pathtofile is funky. JS (for example, funky. if JS is located in the scripts folder in the root directory, the pathtofile value is changed to scripts. funky. JS ). therefore, the value of the webresource parameter is funkytextbox. funky. JS.
The contenttype parameter specifies the MIME type of the resource to be retrieved. when querying an external resource, the browser sends an HTTP request to the server separately. the MIME type informs the browser of the type of data to be returned. for JavaScript files, the corresponding contenttype is text/JavaScript. For more information about mime media types, see the official MIME types list.
Finally, performsubstitution is an optional Boolean value that specifies whether the resource can be referenced by other external resources. for example, you may insert an image file and a Javascript file into the assembly, and the script file may need to reference some image resources. if necessary, set the receivmsubstitution parameter to true.
For the controls used in this article, we use the following attribute declaration to register the external files of funky. JS:
[Assembly: webresource ("funkytextbox. Funky. js", "text/JavaScript")]
After registering a resource, we can use webresource. axd HTTP handler to access it. The rest is to write code to generate the corresponding URL for the external resource.
Therefore, we use the getwebresourceurl (type, webresource) method in the clientscriptmanager class. The type parameter is the type of the control,
The webresource parameter is the value of webresource used in the preceding webresource feature. For example, to obtain a URL to access the built-in funky. js resource from the server control, I implement this:
Page. clientscript. getwebresourceurl (this. GetType (), "funkytextbox. Funky. js ")
In addition, we use the registerclientscriptinclude method and the getwebresourceurl method in the onprerender event of the funkytextbox control, include the corresponding JavaScript (<SCRIPT src = "pathtoexternaljavascriptfile" type = "text/JavaScript">) as follows:
Protected override void onprerender (eventargs E)
{
// When pre-rendering, add in external Javascript file
Page. clientscript. registerclientscriptinclude ("funkyjavascript ",
Page. clientscript. getwebresourceurl (this. GetType (),
"Funkytextbox. Funky. js "));
Base. onprerender (E );
}
With this override onprerender method, the control will add the following tag to the page:
<SCRIPT src = "/testwebsite/webresource. axd? D = NLu6bm6a2XinJZt4M-ujmQ13X5ALig6NEAZa1-AxV0HCbE3M-
Vhnomdqt_qnxjdt0 & t = 632902136868023078 "type =" text/JavaScript "> </SCRIPT>
Here is a funkytextbox:
<Input onkeypress = "changebackgroundcolor (this);" name = "mytextbox" type = "text" id = "mytextbox"/>
In this way, JavaScript is introduced into. webresource. aspx HTTP handler to obtain the built-in resource and send it back to the client.
Conclusion
This article describes how to implant resources into a custom ASP. NET Server Control accessories, and how to access these resources through a URL. this is ASP. NET 2.0, allowing developers to implant external resources into accessories.