Thursday, March 6, 2008

Don't you... forget about me.

How to use RegisterClientScriptResource

I think this is like the third time I've spent more than an hour trying to supply a js-file with the ClientScriptManager.RegisterClientScriptResource method. So here's a little how-to.

  1. Make the js-file an embedded resource by setting the build action in the Properties window.
  2. Add the assembly level WebResourceAttribute for the resource. The name of the resource is a tricky little thing especially since it differs slightly depending between C# and VB, see the section further down about this.
  3. Call the RegisterClientScriptResource-method with a type from the same assembly as the resource is located in as the first argument and the resource name as the second argument anytime before the page is rendered.

Resource name

Resources are named slightly differnetly in C# and VB. In both cases they start with the name of the root namespace of the assembly. Then C# has the folder path (dot-separated). Finally in both cases it ends with the file name of the resource.

For example, let's assume that we have a file named Foo.js located in a folder that's named B, that's in turn located in another folder called A in the assembly Bar, that has the root namespace "Bar". Now the resource will be named in the following in the two languages.

C#
Bar.A.B.Foo.js
VB
Bar.Foo.js
The three times I've spent time on this I've simply forgot about the WebResourceAttribute for the script file, now I've hopefully done that for the last time.

No comments:

Post a Comment