Problem:
I have my application structure similar to as shown below:
My JavaScript file has one function which I want to use on each and every page which used my master page. That JS function looks like:
</font>
<font size="2">function HelloWorld()
{
alert("Helloo.....World...");
}</font>
<font size="2">
And to register a JS file i have registered it on one place which is in MASTER..rather than registering it on each and every page. so my master head looks like this:
</font>
<font size="2">
<head runat="server"> </font>
<font size="2"><script language="javascript" type="text/javascript" src="Javascript/HelloWorld.js">
</script>
</head></font>
<font size="2">
on FormWithMasterPage.aspx. i was calling that function as shown below:
</font>
<font size="2"><asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<input type="button" value="OK" onclick="HelloWorld();" />
</asp:Content></font>
<font size="2">
And it was working as expected..means showing alert message:
but when i tried the same within SubPageDefault.aspx which is under my SubFolder folder it was throwing an error:
Which says that it was unable to find JS function HelloWorld();
In short..How to Add application relative Javascript reference?????
Because for SubPageDefault.aspx function it was trying to find “Javascript/HelloWorld.js” under /SubFolder/javascript/..
Solution:
To solve this problem you need to change bit in your master page head section:
1. Open master page and locate its <HEAD> Section and if it has runat=”server” remove it. [In some case if you are using Themes then it is compulsory to put it..no problem put another head tag with no runat="server".]
2. Hook the code as shown below under <HEAD> for registering JS:
</font>
<font size="2">
<head>
</font><font size="2">
<font color="#0000ff">
<%--To use line as shown below remove runat="server" And if it is required to put runat="server" put one more head with runat="server"--%>
<script language="javascript" type="text/javascript" src='<%=ResolveClientUrl("~/Javascript/HelloWorld.js")%>'></script></font>
</font>
<font size="2"><font color="#ff0000"><%--Line below will not work--%>
<%--<script language="javascript" type="text/javascript" src="Javascript/HelloWorld.js"></script>--%>
</font></head></font>
<font size="2">
That’s it…Happy mastering!!
Source code: http://sites.google.com/site/klpatils/Home/RelativeJSURL.rar?attredirects=0
Links:
http://www.dotnetgenerics.com/Modules/TricksAndTips/ASP.NET/PowerOfTilda.aspx
http://www.odetocode.com/Articles/419.aspx
http://www.odetocode.com/articles/450.aspx – ATOZ of Master Page