views:

401

answers:

5

This may be a painfully simply question for which I will be mocked but I am having difficulty in using filepaths in masterpages. I believe this is because if a page in a sub-directory to using the masterpage then the filepath is incorrect.

To fix this I need to get the filepath from the root but I can't seem to get it working.

I tried:

            <script type="text/javascript" src="~/jQueryScripts/jquery.js"></script>

and

            <script type="text/javascript" src="../jQueryScripts/jquery.js"></script>

No luck on either!

Any ideas on how I can tell it to get the filepath from the root? Thanks :)

+1  A: 

I'm just assuming by filepath, you actually mean url (or uri, I forget which one is partial).

Without the ~, the first example should work. <script type="text/javascript" src="/jQueryScripts/jquery.js"></script> would cause the browser to request http://www.example.com/jQueryScripts/jquery.js (where www.example.com is your domain).

R. Bemrose
+1  A: 

I believe you need to have runat=server in the <head> tag of the MasterPage for this URL rebasing to work.

<head runat="server">
DOK
Yeah, Already have that. No Luck :(
Damien
Well, at least your apprehension about being "mocked out" for asking a "painfully simple" question was unfounded. It turns out to be a challenging issue, and it was a good question. Do let us know which solution works for you.
DOK
+2  A: 

If you're running an AJAX-enabled site, see my answer to Preferred way to include relative reference to JavaScript in VS 2008 nested Masterpage.

Kon
Cheers! That did it!
Damien
+1  A: 

First off the tilde in front is a asp.net thing for use in server controls and won't work in basic HTML.

Without getting into detailed explanations you could just use a slash (/) in front, and include the web app name if its not the root site.

Or you could put code in your master page for dynamically including scripts, and let it handle the pathing. Like:

    public void AddJavascript(string javascriptUrl)
    {   
        HtmlGenericControl script = new HtmlGenericControl("script");
        script.Attributes.Add("type", "text/javascript");
        javascriptUrl += "?v" + Assembly.GetExecutingAssembly().GetName().Version;
        script.Attributes.Add("src", ResolveUrl(javascriptUrl));
        Page.Header.Controls.Add(script);
    }

The above code also appends the assembly version. I use this mostly for development so my javascript files get updated whenever I build.

Jeff Sheldon
+1  A: 

You could use the Page.ResolveUrl method to get around this

for example:

<script type="text/javascript" src="<%=Page.ResolveUrl("~/jQueryScripts/jquery.js")%>"></script>
kristian
I got an HttpException - "The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)." when I tried this.
Daniel Ballinger