views:

1155

answers:

5

I'm working on a C#/ASP.NET project that has all the javascript files in a /Javascript folder. If I refer to the JS file using this syntax: src="/Javascript/jsfile.js" then the file is correctly picked up if the project is deployed to the root of the URL.

However, if this "web site" is deployed to a sub-folder of the main url this won't work. So the solution could be to use relative urls - but there's a problem with that as well because the master pages reference many of the javascript files and these master pages can be used by pages in the root and in subfolders many levels deep.

Does anybody have any ideas for resolving this?

+8  A: 

If you reference the JS-file in a section that is "runat=server" you could write src="~/Javascript/jsfile.js" and it will always work.

You could also do this in your Page_Load (In your masterpage):

Page.ClientScript.RegisterClientScriptInclude("myJsFile", Page.ResolveClientUrl("~/Javascript/jsfile.js"))
Espo
+4  A: 

Try something like this in the Master Page:

<script type="text/javascript" src="<%= Response.ApplyAppPathModifier("~/javascript/globaljs.aspx") %>"></script>

For whatever reason, I've found the browsers to be quite finicky about the final tag, so just ending the tag with /> doesn't seem to work.

Jared
A: 

@Jared: IE needs that /script . FF doesn't care.

erlando
+4  A: 

The brand-new version of ASP.NET (3.5 SP1) has a nifty feature called CompositeScript. This allows you to use a ScriptManager to reference lots of tiny little .js files server-side and have them delivered as a single .js file to the client.

Good for the client since it only has to download one file. Good for you since you can maintain the files however you want on the server side.

<asp:ScriptManager ID="ScriptManager1" 
    EnablePartialRendering="True"
    runat="server">
    <Scripts>
        <asp:ScriptReference 
            Assembly="SampleControl" 
            Name="SampleControl.UpdatePanelAnimation.js" />
    </Scripts>
</asp:ScriptManager>
Brad Tutterow
A: 

You might want to take a look at FileResolver. It's an HTTP Handler that allows you to do this:

<link rel="stylesheet" href="~/resources/stylesheet.css.ashx" />

And have the tilde (as well as any tildes within the file) expanded properly.

Chris Zwiryk