Damien
Damien

Reputation: 14057

Dealing with relative filepaths in ASP.NET and master pages

This may be a painfully simply question for which I will be mocked but I am having difficulty in using filepaths in master pages. I believe this is because if a page in a sub-directory to using the master page 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?

Upvotes: 1

Views: 1295

Answers (4)

kristian
kristian

Reputation: 23039

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

for example:

<script type="text/javascript" src="<%=Page.ResolveUrl("~/jQueryScripts/jquery.js")%>"></script>

Upvotes: 1

Jeff Sheldon
Jeff Sheldon

Reputation: 2094

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.

Upvotes: 1

DOK
DOK

Reputation: 32841

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

<head runat="server">

Upvotes: 1

Powerlord
Powerlord

Reputation: 88796

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).

Upvotes: 2

Related Questions