Introduction
In .net 2.0 it’s very simple to add web resource to the custom control. Following code will describe the method to add web resource to custom control.
Using the code
We have to follow the following steps to add web resource to custom control.
1. Add web resources like JavaScript, Style sheet, image file to your custom control project.
3. Set “Build Action” property to “Embedded Resource”. [Default value is set to “Content”]
4. Add reference to “System.Web” in your project.
5. Add the following to your custom control:
using System.Web.UI;
6. Add assembly reference of “Web Resources” to your project:
[assembly: WebResource("ProjectName.ResourceFileName", "FileType")]
For example:
[assembly: WebResource
("CustomCtrlWithWebResource.MyCssFile.css", "text/css")]
[assembly: WebResource
("CustomCtrlWithWebResource.MyJsFile.js", "text/javascript")]
7. Add following lines to add *.js file
string jsResource = "CustomCtrlWithWebResource.MyJsFile.js";
this.Page.ClientScript.RegisterClientScriptResource(this.GetType(), jsResource);
8. For other resources following code can be used:
string cssResource = "CustomCtrlWithWebResource.MyCssFile.css";
string cssResourceURL = Page.ClientScript.GetWebResourceUrl(this.GetType(), cssResource);
HtmlLink cssLink = new HtmlLink();
cssLink.Href = cssResourceURL;
cssLink.Attributes.Add("rel", "stylesheet");
this.Page.Header.Controls.Add(cssLink);
After adding above mentioned code, our “MyCustomCtrl.cs” file will have following content:
using System;
using System.Web.UI;
using System.Web.UI.HtmlControls;
[assembly: WebResource("CustomCtrlWithWebResource.MyCssFile.css", "text/css")]
[assembly: WebResource("CustomCtrlWithWebResource.MyJsFile.js", "text/javascript")]
namespace CustomCtrlWithWebResource
{
class MyCustomCtrl: Control
{
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
string jsResource = "CustomCtrlWithWebResource.MyJsFile.js";
this.Page.ClientScript.RegisterClientScriptResource(this.GetType(), jsResource);
string cssResource = "CustomCtrlWithWebResource.MyCssFile.css";
string cssResourceURL = Page.ClientScript.GetWebResourceUrl(this.GetType(), cssResource);
HtmlLink cssLink = new HtmlLink();
cssLink.Href = cssResourceURL;
cssLink.Attributes.Add("rel", "stylesheet");
this.Page.Header.Controls.Add(cssLink);
}
}
}
You can add required functionalities to your custom control now and use the embedded resources like “javascript functions”,“cssClass” etc.