When designing a custom control in asp.net, often we have a client side javascript file for the control. We have two options to include the script file: either declare it in asp.net webform directly or embed it in custom control dll file.
In asp.net 1.1 we could include the javascript in the custom control project's resource file and consume the resource at run time. This elimilated the need of the dependent on the external script file. Or we could create a HTTP Module or Handler to handle the script file name. While this works, it requires some extra coding.
In asp.net 2.0 we have a new and simplified approach. We could embed the script file in the external dll file and consume it using the built-in WebResource.axd http handler.
The following is an example of applying this strategy.
I have created a simple custom control to show alert message in a web form. This control simply call javascript alert function.
First I create a Web Control project, with namespace as MyWebControl. Then I create a javascript file Alert.js in the folder JavaScript. There is only one function in the Alert.js:
function ShowAlert(message)
{
alert(message);
}
Then I open the property of this file, change it's Build Action property to Embedded Resource.
By default, any resource in the dll file is not accessible externally. To enable web form access this resource, we need to define it in the AssemblyInfo.cs file:
[assembly: WebResource("MyWebControl.JavaScript.Alert.js", "text/javascript", PerformSubstitution = true)]
Note I also include the control namespace as prefix to the resource name, this is required.
The resource is available now, what we do is to consume it in the control source code. The following function is an example:
protected override void OnPreRender(EventArgs e)
{
ClientScriptManager cs = Page.ClientScript;
if (!cs.IsClientScriptIncludeRegistered("WebAlert"))
{
cs.RegisterClientScriptInclude("WebAlert", cs.GetWebResourceUrl( this.GetType(),
"MyWebControl.JavaScript.Alert.js" ));
} if (Text != string.Empty)
{
string message = Text.Replace("\r", "").Replace("\"", "\\\"").Replace("\n", @"\r\n");
cs.RegisterStartupScript(this.GetType(), "AlertScript", "ShowAlert(\"" + message + "\");", true);
}
Text = string.Empty; // make sure to clear the message to remove the alert for the next page load.
base.OnPreRender(e);
}
That's all we need. After put this control in a webform, asp.net put this line in the html:
The script is cached in the client side so it's downloaded into user's browser only once.
Thursday, 28 September 2006
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment