Working with relative file paths in ASP.Net and Masterpages

This may be a painfully simple question for which I will mock, but I am having a hard time using file paths in masterpages. I believe this is because if a page in a subdirectory is used with the main page, then the file path is incorrect.

To fix this, I need to get the file path from the root, but I cannot get it to work.

I tried:

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

      

and

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

      

Bad luck!

Any ideas on how I can tell to get the file path from the root? Thank:)

+1


source to share


5 answers


I'm just assuming by the file path, you actually mean the 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>

will cause the browser to request http://www.example.com/jQueryScripts/jquery.js (where www.example.com is your domain).

+2


source


If you're on an AJAX-enabled site, see my answer to Preferred Way to Include a JavaScript Relative Link in a VS 2008 Nested Master Page .



+2


source


I suppose you need to have runat=server

in the tag <head>

MasterPage

for this url to be loaded.

<head runat="server">

      

+1


source


The tilde first in front is an asp.net thing for use in server controls and won't work in basic HTML.

Without going into too much detail, you can simply use the forward slash (/) and include the name of the web app if it is not the root site.

Or you can put code on your master page to enable scripting dynamically and let it handle the path. How:

    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 adds the assembly version. I use this mainly for development, so my javascript files are updated every time I create.

+1


source


You can use Page.ResolveUrl method to get around this

eg:

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

      

+1


source







All Articles