It's been a long time since I wrote last post .... The topic for this post is to introduce how to include javascript, images and css styles as web resource to a customized control. The motivation behind this is, most of the times, when we try to develop our own web controls, we would need to add certain embeded javascript files and images to make the control more functional, and css files to make the control looks better. And we are not happy to develop a control and put javascript/css references manually everytime when we refer to the control. Ok, with that in mind, here is the simple steps to follow...
1, Create a class library project say "TestComponents" and make the default namespace as "TestComponents".
2, Add a class named "MyComponents" to the project like below... The bold part are two ways of getting the javascript webresource and register to the page.
public class MyComponents: WebControl, INamingContainer
{
protected override void OnPreRender(EventArgs e)
{
/*Register the resource directly to client script */
this.Page.ClientScript.RegisterClientScriptResource(this.GetType(), "TestComponents.TestScript.js");
/*
* Added javascript as a control manually by referring to GetWebResouceUrl function.
*/
string jsUrl = this.Page.ClientScript.GetWebResourceUrl(this.GetType(), "TestComponents.TestScript.js");
HtmlGenericControl jsTag = new HtmlGenericControl("script");
jsTag.Attributes.Add("type", "text/javascript");
jsTag.Attributes.Add("src", jsUrl);
this.Controls.Add(jsTag);
base.OnPreRender(e);
}
}
3, As you see above, we are referring to a Javascript file "TestScript.js". Obviously, we will need to add the javascript file to the class library project. The key thing here is after adding the file, we need to make the file as "Embedded Resource" like below...

4, And how this js file is associated to a webresource? Open AssemblyInfo.cs file of the class library project and add webresource attributes as below...
[assembly: WebResource("TestComponents.TestScript.js", "text/javascript", PerformSubstitution = true)]
[assembly: WebResource("TestComponents.spinner.gif", "image/gif")] /*This is a simple example of including an image as webresource, of coure you will need to add the file to the project.*/
Thats all! Compile the project and add a reference to the compiled dll from any webpage, create a control instance as we usually do. Run the webpage and click view source, you shall see something like below...
<script src="/WebSite3/WebResource.axd?d=vWXridFtpJVLn9e3g0KBNF7WuB1c4gU48zId1idAQ_EyL_rZfUanNAStBE18a669ws17Aqa0HVzqN0JcoptQu5GHBPhgXGF9UMkp9XCO4UY1&t=633494699620000000" type="text/javascript"></script>