Tuesday, December 23, 2008

Solution to JavaScript File Include Problem From ASP.Net MasterPage

You can include javascript files using a simple script tag. However, you will soon discover that, when you are using this master page from content pages that are at different levels in folder hierarchy then the script files will be missing at some cases. This is due to the fact that, script file paths are referenced relative to the content page and NOT to the master page. As a result, despite having the correct include wrt the master page, your content pages may still miss the scripts!

The solution is simple. Add this following line (of course, replacing the sample values with your own ones) to your master page's page load method to add the script tag through code instead of through markup.

this.Page.ClientScript.RegisterClientScriptInclude("YourKey", ResolveUrl("~/Scripts/myscript.js");

Hope it saves you from the pain of adding a common js file into each of your content pages.