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:)
source to share
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).
source to share
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 .
source to share
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.
source to share