Tuesday, October 6, 2009

Add JavaScript file to Master Page in ASP.NET using code-behind

Sometimes it is necessary to include a JavaScript file in your Master Page or any ASP.NET page. There is no problem if all your pages are in the same directory or not using dynamic data and routing. When you start messing with the pattern of the url, hard coded references to a JavaScript file quickly get broken.

Thankfully, there is a relatively easy way to add the JavaScript file using code-behind.

Page.ClientScript.RegisterClientScriptInclude("Validation.js", ResolveClientUrl("~/jscripts/Validation.js"));

In the above example, I have set the key to “Valiadtion.js”, but this could be anything unique. The second parameter uses the ~ so that the proper path is used when developing in a virtual directory and deploying to a separate web site the url works in both cases.

When the html page is generated and sent to the browser, you will see that path changes depending on what directory your page is in. Which is exactly what we needed; a smart path to the JavaScript file.

2 comments:

Shekel said...

Thanks man! Been searching for a solution for this one... Worked like a charm :)

Brent V said...

Shekel,

So glad it helped. Thx for the feedback.

Brent