Monday 18 July 2011

Dot.Net: Register WebResource Javascript from Different Assembly

Question:
I have a web control project and a web project.
In the web control project I embed a javascript file and declared it as a WebResource in the AssemblyInfo.cs:
[assembly: System.Web.UI.WebResource("Namespace.Folder.MyScript.js", "text/javascript", PerformSubstitution = false)].

When I want to use it from the web project using:
this.Page.ClientScript.RegisterClientScriptResource(this.GetType(), "Namespace.Folder.MyScript.js");
It does not work.
Why is the javascript file not loaded into the page?


Answer:
The ClientScript.RegisterClientScriptResource method takes a type as the first argument.
This type must be one from the assembly that embedded the javascript file.
In our precise case you cannot use the type of your page or control.

Here is an example
protected override void OnPreRender(EventArgs e)
{
    base.OnPreRender(e);

     // the type you use must be a type of the assembly where the javascript is embedded :)
    this.Page.ClientScript.RegisterClientScriptResource(typeof(ATypeOfEmbeddingAssembly), "Namespace.Folder.MyScript.js");
}



No comments: